文章詳情頁
SQL Server實(shí)現(xiàn)查詢每個(gè)分組的前N條記錄
瀏覽:10日期:2023-03-06 14:25:16
SQL語句查詢每個(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開發(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í)管理與開發(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ù)手冊(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. The MySQL server is running with the --read-only option so it cannot execute this statement2. SQL Server 2008數(shù)據(jù)庫引擎優(yōu)化顧問與索引優(yōu)化向?qū)еg的差別3. DB2 與 Microsoft SQL Server 2000 之間的 SQL 數(shù)據(jù)復(fù)制4. sql server里面可能經(jīng)常會(huì)用到的日期格式轉(zhuǎn)換方法5. SQL server分頁的四種方法思路詳解(最全面教程)6. SQL Server數(shù)據(jù)庫超級(jí)管理員賬號(hào)防護(hù)知識(shí)7. sql server 2005中的DDL觸發(fā)器8. 如何禁止遠(yuǎn)程訪問sql server9. Sql Server2005學(xué)習(xí)日記(01)10. SQL Server EXEC和sp_executesql的區(qū)別
排行榜

網(wǎng)公網(wǎng)安備