CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))
where a.qu=b.qu and b.je>=a.je)<=2
ORDER BY qu,je DESC
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je desc)
insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)
要求查询出来的结果如下:
qu co je
----------- ----------- -----
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4
就是要按qu分组,每组中取je最大的前2位!!
而且只能用一句sql语句!!!
where a.qu=b.qu and b.je>=a.je)<=2
ORDER BY qu,je DESC
选出一条记录, 然后做循环.
这么写会好懂一些?
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)
可以这样写:
select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je desc)
本文介绍了一种使用单一SQL语句实现的数据查询方法,该方法可以在每个分组内选取具有最大值的前两条记录。通过对SQL语句的巧妙构造,实现了高效的数据筛选。
&spm=1001.2101.3001.5002&articleId=2049628&d=1&t=3&u=403e6d6279fa461b8a2e156c652534a5)
14万+

被折叠的 条评论
为什么被折叠?



