下文為您介紹的是使用SQL語句查詢每個分組的前N條記錄的實(shí)現(xiàn)方法,如果您在此方面曾經(jīng)遇到過問題,不妨一看,對您學(xué)習(xí)SQL語句使用有所幫助。
- --> 生成測試數(shù)據(jù): #T
- IF OBJECT_ID('tempdb.dbo.#T') IS NOT NULL DROP TABLE #T
- CREATE TABLE #T (ID VARCHAR(3),GID INT,Author VARCHAR(29),Title VARCHAR(39),Date DATETIME)
- INSERT INTO #T
- SELECT '001',1,'鄒建','深入淺出SQLServer2005開發(fā)管理與應(yīng)用實(shí)例','2008-05-10' UNION ALL
- SELECT '002',1,'胡百敬','SQLServer2005性能調(diào)校','2008-03-22' UNION ALL
- SELECT '003',1,'格羅夫Groff.J.R.','SQL完全手冊','2009-07-01' UNION ALL
- SELECT '004',1,'KalenDelaney','SQLServer2005技術(shù)內(nèi)幕存儲引擎','2008-08-01' UNION ALL
- SELECT '005',2,'Alex.Kriegel.Boris.M.Trukhnov','SQL寶典','2007-10-05' UNION ALL
- SELECT '006',2,'飛思科技產(chǎn)品研發(fā)中心','SQLServer2000高級管理與開發(fā)','2007-09-10' UNION ALL
- SELECT '007',2,'胡百敬','SQLServer2005數(shù)據(jù)庫開發(fā)詳解','2008-06-15' UNION ALL
- SELECT '008',3,'陳浩奎','SQLServer2000存儲過程與XML編程','2005-09-01' UNION ALL
- SELECT '009',3,'趙松濤','SQLServer2005系統(tǒng)管理實(shí)錄','2008-10-01' UNION ALL
- SELECT '010',3,'黃占濤','SQL技術(shù)手冊','2006-01-01'UNION ALL
- SELECT '010',4,'黃蛋蛋','SQL技術(shù)手冊蛋蛋','2006-01-01'
-
-
- --SQL查詢?nèi)缦?
-
- --按GID分組,查每個分組中Date最新的前2條記錄
-
- select * from #T
-
- --1.字段ID唯一時(shí):
- SELECT * FROM #T AS T WHERE ID IN(SELECT TOP 3 ID FROM #T WHERE GID=T.GID ORDER BY Date DESC)
-
- --2.如果ID不唯一時(shí):
- SELECT * FROM #T AS T WHERE 2>(SELECT COUNT(*) FROM #T WHERE GID=T.GID AND Date>T.Date)
-
- --SQL Server 2005 使用新方法
-
- --3.使用ROW_NUMBER()進(jìn)行排位分組
- SELECT ID,GID,Author,Title,Date
- FROM
- (
- SELECT rid=ROW_NUMBER() OVER(PARTITION BY GID ORDER BY Date DESC),*
- FROM #T
- ) AS T
- WHERE rid<=2
-
- --4.使用APPLY
- SELECT DISTINCT b.*
- FROM #T AS a
- CROSS APPLY
- (
- SELECT TOP(2) * FROM #T WHERE a.GID=GID ORDER BY Date DESC
- ) AS b
-
-
- select * from #T