SQL statement sorting

Source: Internet
Author: User

1.Add a sequence number column before each result extracted by the SELECT statement, starting from 1. The step size is...

Select (select count (*) from blog a where a. ID <= B. ID) as unid, * From Blog B
2. Tips for using groupby order by top

 

Code
Dedeclare @ t table (ID Int , Dat datetime, userid Int )
Insert into @ t select 1 , Getdate (), 1  
Union all select 2 , Getdate () + 1 , 2
Union all select 3 , Getdate () + 3 , 3
Union all select 3 , Getdate () + 10 , 3
Union all select 5 , Getdate () + 9 , 5

Select top3Userid, max (DAT)AsDat from @ T group by userid order by dat DESC
Execution sequence: group by, Max, order by, and top
Explanation: first, use group by to group users, then use Max to retrieve the unique userids with the maximum time in each group, and then sort these userids in descending order by time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.