首先的建表語句:
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
字段含義:name 風景區名稱,votenum 景區得票數量 ,type 景區類型
實現功能:查詢各分類中投票最多的兩個景區,按投票數從高到低排序
實現1: ROW_NUMBER() 配合partition by 按照分組進行排序,取前兩位,易懂
select name,votenum,[type] from ( select *,ROW_NUMBER() over(partition by [type] order by votenum desc) vn from test) b where b.vn<=2 order by [type], votenum desc
實現2:自連接
select * from test a where (select COUNT(*) from test b where a.type=b.type and a.votenum<b.votenum) <=1 order by [type],votenum desc
外層表a中的一條數據 在內層表b中查找的相同類型type,且b表中投票數量大於a表中該條記錄的投票數量的記錄數(count),
如果小於1,說明a表中的這條數據 的投票數是最高或者是第二高的,則返回a表中的這條數據
實現3:
select * from test a where a.id in(select top 2 b.id from test b where a.type=b.type order by b.votenum desc) order by [type],votenum desc