首页 > 代码库 > groupby以后取每组前n行
groupby以后取每组前n行
----------------------------------- Author: liangCK 小梁-- Title : 查每个分组前N条记录-- Date : 2008-11-13 17:19:23--------------------------------- --> 生成测试数据: #TIF OBJECT_ID(‘tempdb.dbo.#T‘) IS NOT NULL DROP TABLE #TCREATE 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‘--SQL查询如下:--按GID分组,查每个分组中Date最新的前2条记录--1.字段ID唯一时:SELECT * FROM #T AS T WHERE ID IN(SELECT TOP 2 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,DateFROM( SELECT rid=ROW_NUMBER() OVER(PARTITION BY GID ORDER BY Date DESC),* FROM #T) AS TWHERE rid<=2--4.使用APPLYSELECT DISTINCT b.*FROM #T AS aCROSS APPLY( SELECT TOP(2) * FROM #T WHERE a.GID=GID ORDER BY Date DESC) AS b--结果/*ID GID Author Title Date---- ----------- ----------------------------- --------------------------------------- -----------------------003 1 格罗夫Groff.J.R. SQL完全手册 2009-07-01 00:00:00.000004 1 KalenDelaney SQLServer2005技术内幕存储引擎 2008-08-01 00:00:00.000005 2 Alex.Kriegel.Boris.M.Trukhnov SQL宝典 2007-10-05 00:00:00.000007 2 胡百敬 SQLServer2005数据库开发详解 2008-06-15 00:00:00.000009 3 赵松涛 SQLServer2005系统管理实录 2008-10-01 00:00:00.000010 3 黄占涛 SQL技术手册 2006-01-01 00:00:00.000(6 行受影响)*/
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。