欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SQL Server實現(xiàn)查詢每個分組的前N條記錄

 更新時間:2022年06月14日 16:10:02   作者:springsnow  
這篇文章介紹了SQL Server實現(xiàn)查詢每個分組的前N條記錄,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

SQL語句查詢每個分組的前N條記錄的實現(xiàn)方法:

1、生成測試數(shù)據(jù): #T

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開發(fā)管理與應(yīng)用實例', '2008-05-10'
union all
select '002', 1, '胡百敬', 'SQLServer2005性能調(diào)校', '2008-03-22'
union all
select '003', 1, '格羅夫Groff.J.R.', 'SQL完全手冊', '2009-07-01'
union all
select '004', 1, 'KalenDelaney', 'SQLServer2005技術(shù)內(nèi)幕存儲引擎', '2008-08-01'
union all
select '005', 2, 'Alex.Kriegel.Boris.M.Trukhnov', 'SQL寶典', '2007-10-05'
union all
select '006', 2, '飛思科技產(chǎn)品研發(fā)中心', 'SQLServer2000高級管理與開發(fā)', '2007-09-10'
union all
select '007', 2, '胡百敬', 'SQLServer2005數(shù)據(jù)庫開發(fā)詳解', '2008-06-15'
union all
select '008', 3, '陳浩奎', 'SQLServer2000存儲過程與XML編程', '2005-09-01'
union all
select '009', 3, '趙松濤', 'SQLServer2005系統(tǒng)管理實錄', '2008-10-01'
union all
select '010', 3, '黃占濤', 'SQL技術(shù)手冊', '2006-01-01'
union all
select '010', 4, '黃蛋蛋', 'SQL技術(shù)手冊蛋蛋', '2006-01-01';

2、表記錄查詢?nèi)缦?

select * from #T;

結(jié)果:

3、按GID分組,查每個分組中Date最新的前2條記錄

(1)用子查詢

--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);

(2)使用SQL Server 2005 使用新方法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;

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論