文章詳情頁
SQL Server實(shí)現(xiàn)查詢每個(gè)分組的前N條記錄
瀏覽:14日期:2023-03-06 14:25:16
SQL語句查詢每個(gè)分組的前N條記錄的實(shí)現(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 #Tselect "001", 1, "鄒建", "深入淺出SQLServer2005開發(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完全手冊", "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í)管理與開發(fā)", "2007-09-10"union allselect "007", 2, "胡百敬", "SQLServer2005數(shù)據(jù)庫開發(fā)詳解", "2008-06-15"union allselect "008", 3, "陳浩奎", "SQLServer2000存儲(chǔ)過程與XML編程", "2005-09-01"union allselect "009", 3, "趙松濤", "SQLServer2005系統(tǒng)管理實(shí)錄", "2008-10-01"union allselect "010", 3, "黃占濤", "SQL技術(shù)手冊", "2006-01-01"union allselect "010", 4, "黃蛋蛋", "SQL技術(shù)手冊蛋蛋", "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;
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
標(biāo)簽:
MsSQL
相關(guān)文章:
1. 從舊版本SQL Server中重新存儲(chǔ)數(shù)據(jù)2. 詳解sql server中數(shù)據(jù)庫快照工作原理3. SQL Server數(shù)據(jù)庫超級(jí)管理員賬號(hào)防護(hù)知識(shí)4. sql server 2000無法打開1433端口5. SQL Server還原完整備份和差異備份的操作過程6. SQL Server靜態(tài)頁面導(dǎo)出技術(shù)37. sql server修改字段數(shù)據(jù)類型的方法8. windows sql server如何徹底卸載干凈9. Sql Server2005學(xué)習(xí)日記(01)10. MySQL · 最佳實(shí)踐 · SQL Server三種常見備份 已認(rèn)證的機(jī)構(gòu)
排行榜
