首页 热点 业界 科技快讯 数码 电子消费 通信 前沿动态 电商

热头条丨SQLServer实现查询每个分组的前N条记录

2022-06-15 05:57:42 来源 : 软件开发网

SQL语句查询每个分组的前N条记录的实现方法:

1、生成测试数据: #Tif 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;

标签: 技术手册 系统管理 研发中心

相关文章

最近更新
观焦点:超萌相机 2023-03-01 12:29:37
海南百货网 2023-03-01 12:13:44
焦点热讯:宜点充 2023-02-28 10:10:16
天天关注:小铺CEO 2023-02-28 10:07:13
【世界聚看点】KaFit 2023-02-28 09:31:37
葱天下 2023-02-28 09:17:03
渔界竞钓 2023-02-28 08:15:29
焦点快看:鲸奇视频 2023-02-28 06:30:37
环球热议:萝小逗 2023-02-27 23:25:49
简讯:小码公交 2023-02-27 23:16:12
彼岸花 2023-02-27 22:32:52
时时夺宝 2023-02-27 21:37:50
天天动态:袜之源 2023-02-27 21:29:50
天天资讯:AI空气 2023-02-27 20:19:46
世界时讯:绘读 2023-02-27 20:19:41
看点:一元得购 2023-02-27 19:26:28