文章詳情頁(yè)
SQL Server實(shí)現(xiàn)查詢每個(gè)分組的前N條記錄
瀏覽:25日期:2023-03-06 14:25:16
SQL語(yǔ)句查詢每個(gè)分組的前N條記錄的實(shí)現(xiàn)方法:
1、生成測(cè)試數(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 #Tselect "001", 1, "鄒建", "深入淺出SQLServer2005開(kāi)發(fā)管理與應(yīng)用實(shí)例", "2008-05-10"union allselect "002", 1, "胡百敬", "SQLServer2005性能調(diào)校", "2008-03-22"union allselect "003", 1, "格羅夫Groff.J.R.", "SQL完全手冊(cè)", "2009-07-01"union allselect "004", 1, "KalenDelaney", "SQLServer2005技術(shù)內(nèi)幕存儲(chǔ)引擎", "2008-08-01"union allselect "005", 2, "Alex.Kriegel.Boris.M.Trukhnov", "SQL寶典", "2007-10-05"union allselect "006", 2, "飛思科技產(chǎn)品研發(fā)中心", "SQLServer2000高級(jí)管理與開(kāi)發(fā)", "2007-09-10"union allselect "007", 2, "胡百敬", "SQLServer2005數(shù)據(jù)庫(kù)開(kāi)發(fā)詳解", "2008-06-15"union allselect "008", 3, "陳浩奎", "SQLServer2000存儲(chǔ)過(guò)程與XML編程", "2005-09-01"union allselect "009", 3, "趙松濤", "SQLServer2005系統(tǒng)管理實(shí)錄", "2008-10-01"union allselect "010", 3, "黃占濤", "SQL技術(shù)手冊(cè)", "2006-01-01"union allselect "010", 4, "黃蛋蛋", "SQL技術(shù)手冊(cè)蛋蛋", "2006-01-01";
2、表記錄查詢?nèi)缦?
select * from #T;
結(jié)果:
3、按GID分組,查每個(gè)分組中Date最新的前2條記錄
(1)用子查詢
--1.字段ID唯一時(shí): select *from #T as Twhere ID in (select top 2 ID from #T where GID=T.GID order by Date desc);--2.如果ID不唯一時(shí): select *from #T as Twhere 2>(select count(*)from #T where GID=T.GID and Date>T.Date);
(2)使用SQL Server 2005 使用新方法ROW_NUMBER()進(jìn)行排位分組
select ID, GID, Author, Title, Datefrom( select rid=row_number() over (partition by GID order by Date desc), * from #T) as Twhere rid<=2;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
標(biāo)簽:
MsSQL
相關(guān)文章:
1. SQL Server 2005日志文件損壞的處理方法2. sql server 2005 批量導(dǎo)入導(dǎo)出3. SQL Server 2012 搭建數(shù)據(jù)庫(kù)AlwaysOn(數(shù)據(jù)庫(kù)高可用集群)4. SQL SERVER中的流程控制語(yǔ)句5. Sql Server下數(shù)據(jù)庫(kù)鏈接的使用方法6. sql server刪除數(shù)據(jù)庫(kù)文件的方法7. SQL SERVER 2005 同步復(fù)制技術(shù)8. SQL Server 2005數(shù)據(jù)加密技術(shù)的實(shí)際應(yīng)用9. 如何手動(dòng)刪除 SQL Server 2000 默認(rèn)實(shí)例、命名實(shí)例或虛擬實(shí)例10. SQL Server使用PIVOT與unPIVOT實(shí)現(xiàn)行列轉(zhuǎn)換
排行榜
