注:sqlserver下
create table test
areaid int,
score int
insert into test select 0,10
union all select 0,20
union all select 0,30
union all select 0,40
union all select 0,50
union all select 1,10
union all select 1,20
union all select 1,30
union all select 1,40
union all select 1,50
union all select 2,10
union all select 2,20
union all select 2,30
union all select 2,40
union all select 2,50
goselect * from test
--第一種方法適用於sql2000和,其**如下:
select * from test a
where checksum(*) in (select top 3 checksum(*) from test b where a.areaid=b.areaid order by score desc)
--第二種方法是利用sql2005的函式row_number,其**如下:
(1)with test1 as
select *,
row_number() over (partition by areaid order by score desc) as 'rownumber'
from test
select *
from test1
where rownumber between 1 and 3;
(2)select areaid,score from(
select *,row_number() over(partition by areaid order by areaid desc) row_number from test) a where row_number<6 and row_number>2
select distinct t.* from test a
(select top 3 areaid,score from test
where a.areaid=areaid order by score desc) as t
sql取每個分組的第一行資料
select a.* from table1 a inner join (
select max(a + b)time from table1
group by c ) b
on a.a + a.b = b.time
當然sql2005 的row_number讓很多問題有多種解法:
select * from (select t.*, rank()
over (partition by t.a order by t.b desc) as drank
from table1 t) a where drank=1
分組查詢前幾條資料
create table t id varchar 3 gid int,author varchar 29 title varchar 39 date datetime insert into tselect 001 1,鄒建 深入淺出sqlserver2005開發管理與應用例項 2008 05 1...
分組查詢前幾條資料
create table t id varchar 3 gid int,author varchar 29 title varchar 39 date datetime insert into tselect 001 1,鄒建 深入淺出sqlserver2005開發管理與應用例項 2008 05 1...
hive分組去前幾條資料
交易系統,財務要求維護每個使用者首個交易完成的訂單資料 首單表,可取每個使用者交易完成時間最老的訂單資料 舉例 簡寫版的表結構 表資料 則 財務希望彙總記錄如下 uidorder id service completion time244 2017 02 03 12 23 01.0333 2017 ...