关于sql的query,如何选择每个id的前n项?

来源:百度知道 编辑:UC知道 时间:2024/06/27 19:08:31
我有一个表,大概内容是这样:
id 产量
1 10
1 20
1 30
3 70
3 25
3 40
3 50
。。。。。。。。。。。
我想选择每个不同的id的前2个,顺序是从高到低,比如,上表选出来应该是:
id 产量
1 30
1 20
3 70
3 50

请问如何写这个query?
谢谢!

如果是在sql 2005中的话:
with a as(
select id,产量,row_number() over(partition by id order by 产量 desc)
from 表)
select * from a where a<3

如果是sql 2000的话:
select * from (
select id,产量,(select count(*) from 表 as a2 where a2.id=a1.id and a2.产量>=a1.产量) as rank from
表 as a1) as b
where rank<3
order by id,n desc

SQL2000之前的版本不能处理并列的情况如:前几名的一样产量,这样的情况下用临时表新增一个标识列:select *,col=identity(int,1,1) from table order by ID asc,产量 desc

SQL05以上版本,row_number\rank\dense_rank排序函数,参照联机
或用cross apply处理
--> -->

if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[产量] int)
Insert #T
select 1,10 union all
select 1,20 union all
select 1,30 union all
select 3,70 union all
select 3,25 union all
select 3,40 union all
select 3,50
Go
select
t2.*
from
(Select distinct [id] from #