分組查詢前幾條資料

2021-09-22 11:22:47 字數 2328 閱讀 4414

create

table

#t (id 

varchar(3

),gid 

int,author 

varchar(29

),title 

varchar(39

),date 

datetime

)insert

into

#tselect

'001',

1,'鄒建

','深入淺出sqlserver2005開發管理與應用例項',

'2008-05-10

'union

allselect

'002',

1,'胡百敬',

'sqlserver2005效能調校',

'2008-03-22

'union

allselect

'003',

1,'格羅夫groff.j.r.',

'sql完全手冊',

'2009-07-01

'union

allselect

'004',

1,'kalendelaney',

'sqlserver2005技術內幕儲存引擎',

'2008-08-01

'union

allselect

'005',

2,'alex.kriegel.boris.m.trukhnov',

'sql寶典',

'2007-10-05

'union

allselect

'006',

2,'飛思科技產品研發中心',

'sqlserver2000高階管理與開發',

'2007-09-10

'union

allselect

'007',

2,'胡百敬',

'sqlserver2005資料庫開發詳解',

'2008-06-15

'union

allselect

'008',

3,'陳浩奎',

'sqlserver2000儲存過程與xml程式設計',

'2005-09-01

'union

allselect

'009',

3,'趙松濤',

'sqlserver2005系統管理實錄',

'2008-10-01

'union

allselect

'010',

3,'黃佔濤',

'sql技術手冊',

'2006-01-01'--

sql查詢如下:

--按gid分組,查每個分組中date最新的前2條記錄

--1.欄位id唯一時:

select

*from

#t as

t where

id in

(select

top2

id from

#t where

gid=

t.gid 

order

bydate 

desc)--

2.如果id不唯一時:

select

*from

#t as

t where

2>

(select

count(*

) from

#t where

gid=

t.gid 

anddate

>

t.date)

--sql server 2005 使用新方法

--3.使用row_number()進行排位分組

select

id,gid,author,title,date

from

(select

rid=

row_number() 

over

(partition 

bygid 

order

bydate 

desc),*

from

#t) ast

where

rid<=2--

select

distinctb.*

from

#t as

across

select

top(2) 

*from

#t where

a.gid

=gid 

order

bydate 

desc

) asb

分類: 

分組查詢前幾條資料

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 ...

SQL查詢前幾條資料的方法

sql在不同資料庫查詢前幾條資料 1.oracle select from table1 where rownum n hql from table1 t order by t.createtime desc where rownum n 2.informix select first n from...