日期:2014-05-17 浏览次数:20567 次
-->try ;with t1 as ( select id,name,gradetypeid,brownum,age,meteid from [user] ), t2 as ( select id, gradename,gradeid,gradetypeid,gradetypename,meteid from [grade] ) select c.gradename,a.* from t1 a,t2 c where [brownum]IN (select top 2 [brownum] from t1 b where a.[gradename]=b.[gradename] order by [brownum] desc) and a.id=c.id ORDER BY [gradename] ,[brownum] DESC
------解决方案--------------------
WITH cte1 AS (SELECT id, name, gradetypeid, brownum, age, meteid FROM [user]) , cte2 AS (SELECT id, gradename, gradeid, gradetypeid, gradetypename, meteid FROM [grade]) SELECT c.gradename, a.* FROM cte1 a, cte2 c WHERE [brownum] IN (SELECT top 2 [brownum] FROM cte1 b WHERE a.[gradename] = b.[gradename] ORDER BY [brownum] DESC) AND a.id = c.id ORDER BY [gradename], [brownum] DESC
------解决方案--------------------
CREATE TABLE User1(id int,name varchar(10),gradetypeid int,brownum int,age int,meteid int) INSERT INTO User1 SELECT 1,'张三',1,11,7,1 UNION ALL SELECT 8,'张四',2,16,8, 2 UNION ALL SELECT 2,'张五',2,17,7, 3 UNION ALL SELECT 4 ,'张六',3,16,9, 4 UNION ALL SELECT 6 ,'张七',3,18,7, 5 UNION ALL SELECT 5 ,'张八',2,19,9, 6 UNION ALL SELECT 3 ,'张九',2,21,10,7 UNION ALL SELECT 7 ,'张十',3,41,7, 8 UNION ALL SELECT 9 ,'李一',1,71,7, 9 UNION ALL SELECT 10,'李二',3,99,7, 10 UNION ALL SELECT 11,'李四',1,88,10, 11 CREATE TABLE User2(id int, gradename varchar(10),gradeid int,gradetypeid int,gradetypename varchar(10),meteid int) INSERT INTO User2 SELECT 1,'一年级',1 ,1 ,'小学', 1 UNION ALL SELECT 8,'二年级', 2 ,2 ,'初中', 2 UNION ALL SELECT 2,'二年级', 2 ,2 ,'初中', 3 UNION ALL SELECT 4,'四年级', 4 ,3 ,'高中', 4 UNION ALL SELECT 6,'三年级', 3 ,3 ,'高中', 5 UNION ALL SELECT 5,'二年级', 2 ,2 ,'初中', 6 UNION ALL SELECT 3,'四年级', 4 ,2 ,'初中', 7 UNION ALL SELECT 7,'一年级', 1 ,3 ,'高中', 8 UNION ALL SELECT 9,'一年级', 1 ,1 ,'小学', 9 UNION ALL SELECT 10,'三年级', 3 ,3 ,'高中', 10 UNION ALL SELECT 11,'四年级', 4 ,1 ,'小学', 11 select * from ( SELECT ROW_NUMBER() OVER (partition by T0.gradename ORDER BY bROWnUM DESC) ids,T0.id,name,gradename,T1.gradetypeid,brownum,age FROM User2 T0 LEFT JOIN User1 T1 ON T0.id = T1.id ) A0 where ids<=2 order by brownum /* ids