日期:2014-05-18  浏览次数:20578 次

求写一个SQL语句,分组查询!
表TB如下:

  type val
-------------------------
  A 3
  A 7
  B 2
  C 12
  A 23
  A 33
  C 29
  C 10
  B 13
  B 56
  C 21
  …… ……
通过分组查询,得到分组里的倒序排序里的前三个数字。
得到的表:

  type val
------------------------
  A 33
  A 23
  A 7
  B 56
  B 13
  B 2 
  C 29
  C 21  
  C 10

另:type可能很多,还有D,E,F等

------解决方案--------------------
SQL code

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)
*/

------解决方案--------------------
SQL code

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