日期:2014-05-18 浏览次数:20578 次
create table tb (type char(1), val int) insert into tb select 'A', 3 union all select 'A', 7 union all select 'B', 2 union all select 'C', 12 union all select 'A', 23 union all select 'A', 33 union all select 'C', 29 union all select 'C', 10 union all select 'B', 13 union all select 'B', 56 union all select 'C', 21 with t as (select row_number() over(partition by [type] order by val desc) rn, [type],[val] from tb ) select [type],[val] from t where rn<=3 /* type val ---- ----------- A 33 A 23 A 7 B 56 B 13 B 2 C 29 C 21 C 12 (9 row(s) affected) */
------解决方案--------------------
select type ,val from ( select type ,val,row_number() over(partition by type order by val desc) as rn from TB) a where a.rn<=3