使用SQL语句查询每个分组的前N条记录


--> 生成测试数据: #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开发管理与应用实例','2008-05-10' UNION ALL
Select '002',1,'胡百敬','SQLServer2005性能调校','2008-03-22' UNION ALL
Select '003',1,'格罗夫Groff.J.R.','SQL完全手册','2009-07-01' UNION ALL
Select '004',1,'KalenDelaney','SQLServer2005技术内幕存储引擎','2008-08-01' UNION ALL
Select '005',2,'Alex.Kriegel.Boris.M.Trukhnov','SQL宝典','2007-10-05' UNION ALL
Select '006',2,'飞思科技产品研发中心','SQLServer2000高级管理与开发','2007-09-10' UNION ALL
Select '007',2,'胡百敬','SQLServer2005数据库开发详解','2008-06-15' UNION ALL
Select '008',3,'陈浩奎','SQLServer2000存储过程与XML编程','2005-09-01' UNION ALL
Select '009',3,'赵松涛','SQLServer2005系统管理实录','2008-10-01' UNION ALL
Select '010',3,'黄占涛','SQL技术手册','2006-01-01'UNION ALL
Select '010',4,'黄蛋蛋','SQL技术手册蛋蛋','2006-01-01'


--SQL查询如下:

--按GID分组,查每个分组中Date最新的前2条记录

select * from #T

--1.字段ID唯一时:
Select * FROM #T AS T Where ID IN(Select TOP 3 ID FROM #T Where GID=T.GID orDER BY Date DESC)

--2.如果ID不唯一时:
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()进行排位分组
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


文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: 4498
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 支持Gravatar头像.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭