[SQL Server] Paging-repeated fields + primary keys

Source: Internet
Author: User

-- Test environment

If object_id ('tb') is not null drop table TB
Go
Create Table TB
(
Id int,
Name varchar (20 ),
Constraint pk_tb primary key (ID)
 
)
Go
Insert TB
Select 1, 'A' Union all
Select 2, 'B' Union all
Select 3, 'B' Union all
Select 4, 'B' Union all
Select 5, 'B' Union all
Select 6, 'B' Union all
Select 7, 'B' Union all
Select 8, 'B' Union all
Select 9, 'A' Union all
Select 10, 'A' Union all
Select 11, 'A'
Go
-- Pagination by name

-- Pagination by name
-- Query the first page
Select top 5 * from TB order by name, ID
-- Result
/*
ID name
-------------------------------
1
9
10
11
2 B

(5 rows affected)
*/

-- Query the second page
Select top 5 * from
(
Select top 10 * from TB order by name, ID
) T order by name DESC, Id DESC
-- Result
/*
ID name
-------------------------------
7 B
6 B
5 B
4 B
3 B

(5 rows affected)
*/

-- Query the second page
Select top 5 * from
(
Select top 15 * from TB order by name, ID
) T order by name DESC, Id DESC
-- Result
/*
ID name
-------------------------------
7 B
6 B
5 B
4 B
3 B

(5 rows affected)
*/

Related Article

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.