--> 生成测试数据: #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 ALLSELECT '002','胡百敬','sqlServer2005性能调校','2008-03-22' UNION ALL SELECT '003','格罗夫Groff.J.R.','sql完全手册','2009-07-01' UNION ALL SELECT '004','KalenDelaney','sqlServer2005技术内幕存储引擎','2008-08-01' UNION ALL SELECT '005',2,'Alex.KrIEgel.Boris.M.Trukhnov','sql宝典','2007-10-05' UNION ALL SELECT '006','飞思科技产品研发中心','sqlServer2000高级管理与开发','2007-09-10' UNION ALL SELECT '007','sqlServer2005数据库开发详解','2008-06-15' UNION ALL SELECT '008',3,'陈浩奎','sqlServer2000存储过程与XML编程','2005-09-01' UNION ALL SELECT '009','赵松涛','sqlServer2005系统管理实录','2008-10-01' UNION ALL SELECT '010','黄占涛','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
查询一个客户对应最后一天下单的的单据信息:
SELECT * FROM (select TD001+'-'+rtrim(TD002)+'-'+TD003 document,TC003,TD004,TD005,TD006,CONVERT(decimal(10,2),TD008) TD008,4),TD011) TD011,TD012 from copTC INNER JOIN copTD ON TC001=TD001 AND TC002=TD002WHERE TC004='AZ-0005') AS T WHERE 1>(SELECT COUNT(*) FROM (select TD001+'-'+rtrim(TD002)+'-'+TD003 document,TD012 from copTC INNER JOIN copTD ON TC001=TD001 AND TC002=TD002WHERE TC004='AZ-0005') AS T1 WHERE T1.TD004=T.TD004 AND T1.TC003>T.TC003 AND T1.document>T.document) ORDER BY T.TD004,T.TC003 asc
铁观音-厂家直销 总结
以上是内存溢出为你收集整理的[MSSQL]语句查询每个分组的前N条记录的实现方法全部内容,希望文章能够帮你解决[MSSQL]语句查询每个分组的前N条记录的实现方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)