日期:2014-05-18 浏览次数:20483 次
--> 生成测试数据: #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
------解决方案--------------------
select * from (select a.*,row=row_number()over(partition by a.CLASSID order by newID()) from table1 as a inner join (select CLASSID from table1 group by CLASSID having count(*)>1) as b on a.CLASSID=b.CLASSID) as a where row<3