一、建表
if exists (select * from sysobjects where id = OBJECT_ID('[test]') and OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE [test]
CREATE TABLE [test] ( [id] [int] IDENTITY (1, 1) NOT NULL , [name] [nvarchar] (50) NULL , [votenum] [int] NULL , [type] [nvarchar] (50) NULL )
ALTER TABLE [test] WITH NOCHECK ADD CONSTRAINT [PK_test] PRIMARY KEY NONCLUSTERED ( [id] )
SET IDENTITY_INSERT [test] ON
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 1 , '嶂石岩' , 88 , '风景' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 2 , '云梦山' , 99 , '风景' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 3 , '抱犊寨' , 59 , '风景' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 4 , '崆山白云洞' , 46 , '风景' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 5 , '扁鹊庙' , 56 , '古迹' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 6 , '金长城' , 22 , '古迹' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 7 , '避暑山庄' , 69 , '古迹' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 8 , '西柏坡' , 87 , '古迹' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 9 , '塞罕坝' , 48 , '草原' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 10 , '草原天路' , 44 , '草原' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 11 , '京北草原' , 36 , '草原' )
INSERT [test] ( [id] , [name] , [votenum] , [type] ) VALUES ( 12 , '美林谷' , 77 , '草原' )
SET IDENTITY_INSERT [test] OFF
二、说明
1、字段含义:name 风景区名称,votenum 景区得票数量 ,type 景区类型
2、实现功能:分页查出5-10条的数据,按id倒序排列并且相同的景区类型只取前两个
三、实现
1、实现分页
SELECT * FROM (
select *,ROW_NUMBER() over(order by id desc) row from test) T
WHERE T.row BETWEEN 1 AND 6
2、实现分组并去除组内前两条数据
select * from (
select *,ROW_NUMBER() over(partition by [type] order by id desc) vn from test) b
where b.vn<=2
三、实现分页+分组
SELECT * FROM (
select *,ROW_NUMBER() over( order by id desc) row from (select * from (
select *,ROW_NUMBER() over(partition by [type] order by id desc) vn from test WHERE id < 12) b
where b.vn<=2)bb) T
WHERE t.row BETWEEN 5 AND 10
三、总结
本文要点:第一步使用partition by函数对表格进行分组排序并每组只取前两个,第二步是使用sql分页的方式对第一步获取的数据进行分页
四、感谢
本文部分内容引用自
http://www.cnblogs.com/zhouxiuquan/p/4848765.html