SQL查詢每個分組的前N條記錄

2021-05-26 05:58:32 字數 1493 閱讀 8734

if object_id('tempdb.dbo.#t') is not null drop table #t

create table #t (id varchar(3),gid int,author varchar(29),title varchar(39),date datetime)

insert into #t

select '001',1,'鄒建','深入淺出sqlserver2005開發管理與應用例項','2008-05-10' union all

select '002',1,'胡百敬','sqlserver2005效能調校','2008-03-22' union all

select '003',1,'格羅夫groff.j.r.','sql完全手刪','2009-07-01' union all

select '004',1,'kalendelaney','sqlserver2005技術內幕儲存引擎','2008-08-01' union all

select '005',2,'alex.kriegel.boris.m.trukhnov','sql寶典','2007-10-05' union all

select '006',2,'飛思科技產品研發中心','sqlserver2000高階管理與開發','2007-09-10' union all

select '007',2,'胡百敬','sqlserver2005資料庫開發詳解','2008-06-15' union all

select '008',3,'陳浩奎','sqlserver2000儲存過程與xml程式設計','2005-09-01' union all

select '009',3,'趙松濤','sqlserver2005系統管理實錄','2008-10-01' union all

select '010',3,'黃佔濤','sql技術手冊','2006-01-01'

--sql查詢如下:

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

--1.欄位id唯一時:

select * from #t as t where id in(select top 2 id from #t where gid=t.gid order by date desc)

--2.如果id不唯一時:

select * from #t as t where 2>(select count(*) from #t where gid=t.gid and date>t.date)

--sqlserver 2005 使用新方法

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

select id,gid,author,title,date

from

( select rid=row_number()

over(partition by gid

order by date desc),

* from #t

) as t

where rid<=2

SQL查詢每個分組的前N條記錄

在寫乙個儲存過程中,遇到了乙個問題,自己寫的 sql總是執行效率太低,於是上網搜尋,學到了乙個新招,都怪自己平時不愛學習啊,不過這個語法真的很厲害。需求 取乙個表中每個 id的最新三條資料 按照更新時間倒序取 select from t as t where 3 select count from ...

SQL語句查詢每個分組的前N條記錄的實現方法

生成測試資料 t if object id tempdb.dbo.t is notnull drop table t create table t id varchar 3 gid int,author varchar 29 title varchar 39 date datetime insert...

orcale 查詢分組後的前n條記錄

orcale 查詢分組後的前n條記錄 使用row number over partition by col1,col2 order by col3 desc 示例如下 select from select col1,col2,col4,row number over partition by col...