首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求个SQL语句或存储过程解决方案

2012-03-21 
求个SQL语句或存储过程需求:共100条记录,按20个类别划分,每个分类是5条记录实现:从每个分类中随机取两条记

求个SQL语句或存储过程
需求:
共100条记录,按20个类别划分,每个分类是5条记录

实现:
从每个分类中随机取两条记录,然后合并到一起再随机排序


如果只是随机取可以用NEWID()函数就能实现,现在关键要先在每个分类中随机两条记录然后合并,另外,最好能在随机取两条记录之前加一个判断,判断是否最少有两条记录,保证最后的总数是40条记录。


字段暂定:
ID CLASSID TITLE

[解决办法]

SQL code
--> 生成测试数据: #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'UNION ALLSelect '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,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 bselect * from #T
[解决办法]
SQL code
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 awhere row<3 

热点排行