SQL Grouping sorting paging (big God help to write the worship of a bit)

Source: Internet
Author: User


Query all:

SELECT p3.id, P3. Name, P3. Addtime
From (SELECT Name, MAX (addtime) as Maxaddtime
From Product as P1
GROUP by Name) as P2
INNER JOIN Product as P3 on P2. Name = P3. Name
ORDER by P2. Maxaddtime DESC, P3. Addtime desc, p3.id desc


Pagination of the front and back top method (5 rows per page, 5th page, i.e. 第21-25 rows of data)
(1) Take the first 25 lines in the order required, (2) Top 5 lines, (3) reverse the order back

SELECT p5.id, P5. Name, P5. Maxaddtime
From
(SELECT TOP 5 p4.*
From
(SELECT TOP p3.id, P3. Name, P3. Addtime, P2. Maxaddtime
From
(SELECT Name, MAX (addtime) as Maxaddtime
From Product as P1
GROUP by Name) as P2
INNER JOIN Product as P3 on P2. Name = P3. Name
ORDER by P2. Maxaddtime DESC, P3. Addtime desc, p3.id desc) as P4
ORDER by P4. Maxaddtime, P4. Addtime, p4.id) as P5
ORDER by P5. Maxaddtime DESC, P5. Addtime desc, p5.id desc

Row_number method (for SQL Server 2005 or more)
(5 rows per page, check the 5th page, that is, 第21-25 rows of data)

SELECT p4.id, P4. Name, P4. Addtime
From
(SELECT p3.id, P3. Name, P3. Addtime, Row_number () over (ORDER by P2. Maxaddtime DESC, P3. Addtime desc, p3.id desc) as RN
From
(SELECT Name, MAX (addtime) as Maxaddtime
From Product as P1
GROUP by Name) as P2
INNER JOIN Product as P3 on P2. Name = P3. Name) as P4
WHERE P4. RN between and 25

SQL Group Sorting paging (the big God helps to write the worship of a bit)

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.