文章详情页
SQL Server实现查询每个分组的前N条记录
SQL语句查询每个分组的前N条记录的实现方法:
1、生成测试数据: #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 #Tselect "001", 1, "邹建", "深入浅出SQLServer2005开发管理与应用实例", "2008-05-10"union allselect "002", 1, "胡百敬", "SQLServer2005性能调校", "2008-03-22"union allselect "003", 1, "格罗夫Groff.J.R.", "SQL完全手册", "2009-07-01"union allselect "004", 1, "KalenDelaney", "SQLServer2005技术内幕存储引擎", "2008-08-01"union allselect "005", 2, "Alex.Kriegel.Boris.M.Trukhnov", "SQL宝典", "2007-10-05"union allselect "006", 2, "飞思科技产品研发中心", "SQLServer2000高级管理与开发", "2007-09-10"union allselect "007", 2, "胡百敬", "SQLServer2005数据库开发详解", "2008-06-15"union allselect "008", 3, "陈浩奎", "SQLServer2000存储过程与XML编程", "2005-09-01"union allselect "009", 3, "赵松涛", "SQLServer2005系统管理实录", "2008-10-01"union allselect "010", 3, "黄占涛", "SQL技术手册", "2006-01-01"union allselect "010", 4, "黄蛋蛋", "SQL技术手册蛋蛋", "2006-01-01";
2、表记录查询如下:
select * from #T;
结果:
3、按GID分组,查每个分组中Date最新的前2条记录
(1)用子查询
--1.字段ID唯一时: select *from #T as Twhere ID in (select top 2 ID from #T where GID=T.GID order by Date desc);--2.如果ID不唯一时: select *from #T as Twhere 2>(select count(*)from #T where GID=T.GID and Date>T.Date);
(2)使用SQL Server 2005 使用新方法ROW_NUMBER()进行排位分组
select ID, GID, Author, Title, Datefrom( select rid=row_number() over (partition by GID order by Date desc), * from #T) as Twhere rid<=2;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
标签:
MsSQL
上一条:SQL中的连接查询详解下一条:SQL Server备份数据库的完整步骤
相关文章:
排行榜