sqlserver巧用row_number和partition by分組取top數(shù)據(jù)
--1.創(chuàng)建測試表
create table #score
(
name varchar(20),
subject varchar(20),
score int
)
--2.插入測試數(shù)據(jù)
insert into #score(name,subject,score) values('張三','語文',98)
insert into #score(name,subject,score) values('張三','數(shù)學(xué)',80)
insert into #score(name,subject,score) values('張三','英語',90)
insert into #score(name,subject,score) values('李四','語文',88)
insert into #score(name,subject,score) values('李四','數(shù)學(xué)',86)
insert into #score(name,subject,score) values('李四','英語',88)
insert into #score(name,subject,score) values('李明','語文',60)
insert into #score(name,subject,score) values('李明','數(shù)學(xué)',86)
insert into #score(name,subject,score) values('李明','英語',88)
insert into #score(name,subject,score) values('林風(fēng)','語文',74)
insert into #score(name,subject,score) values('林風(fēng)','數(shù)學(xué)',99)
insert into #score(name,subject,score) values('林風(fēng)','英語',59)
insert into #score(name,subject,score) values('嚴(yán)明','英語',96)
--3.取每個(gè)學(xué)科的前3名數(shù)據(jù)
select * from
(
select subject,name,score,ROW_NUMBER() over(PARTITION by subject order by score desc) as num from #score
) T where T.num <= 3 order by subject
--4.刪除臨時(shí)表
truncate table #score
drop table #score
語法形式:ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2)
解釋:根據(jù)COL1分組,在分組內(nèi)部根據(jù) COL2排序,而此函數(shù)計(jì)算的值就表示每組內(nèi)部排序后的順序編號(組內(nèi)連續(xù)的唯一的)
相關(guān)文章
Sql Server 2005中查詢用分隔符分割的內(nèi)容中是否包含其中一個(gè)內(nèi)容
Sql Server 2005中查詢用分隔符分割的內(nèi)容中是否包含其中一個(gè)內(nèi)容,多個(gè)朋友給予的參考。2011-10-10SQL Server創(chuàng)建維護(hù)計(jì)劃失?。⊿QL Server:14234 錯(cuò)誤)的解決方法
這篇文章主要介紹了SQL Server創(chuàng)建維護(hù)計(jì)劃失?。⊿QL Server:14234 錯(cuò)誤)的解決方法,最后使用SQLServer2005 安裝向?qū)Ы鉀Q問題,需要的朋友可以參考下2014-08-08sqlserver2005 安裝圖解教程以及SQL 2005 SP3補(bǔ)丁安裝圖文教程
最近整理一些sql2005的安裝教程,好多朋友慢慢開始使用sql2005,進(jìn)行開發(fā)了,嘗試新事物。2009-08-08SQL Server CROSS APPLY和OUTER APPLY的應(yīng)用詳解
SQL Server數(shù)據(jù)庫操作中,在2005以上的版本新增加了一個(gè)APPLY表運(yùn)算符的功能2011-10-10SQL2005 學(xué)習(xí)筆記 窗口函數(shù)(OVER)
SQL Server 2005中的窗口函數(shù)幫助你迅速查看不同級別的聚合,通過它可以非常方便地累計(jì)總數(shù)、移動平均值、以及執(zhí)行其它計(jì)算。2009-07-07mdf文件和ldf文件導(dǎo)入到sql server 2005實(shí)現(xiàn)語句
導(dǎo)入mdf文件和ldf文件到數(shù)據(jù)庫是網(wǎng)站搬家或者是初學(xué)者學(xué)習(xí)源碼是必要的一步,接下來為大家詳細(xì)介紹實(shí)現(xiàn)sql語句,感興趣的你可不要錯(cuò)過了哈希望可以幫助到你2013-03-03無法在com+ 目錄中安裝和配置程序集 錯(cuò)誤:-2146233087的解決方法[已測]
最近從腳本之家下載sql2005的部分朋友反應(yīng)無法安裝sql2005,今天在安裝SQL Server2005時(shí)碰到了這個(gè)錯(cuò)誤,到網(wǎng)上搜了一下,找到了解決辦法,特記在這里,以備以后需要。2012-10-10sql2005數(shù)據(jù)導(dǎo)出方法(使用存儲過程導(dǎo)出數(shù)據(jù)為腳本)
在數(shù)據(jù)庫中使用下面的腳本創(chuàng)建存儲過程,然后執(zhí)行存儲過程,參數(shù)為表名,就可以把表的數(shù)據(jù)輸出為SQL腳本2014-01-01SQL Server 移動系統(tǒng)數(shù)據(jù)庫
SQL Server中系統(tǒng)數(shù)據(jù)庫有master、model、msdb、tempdb四個(gè)數(shù)據(jù)庫,對于一般的庫,我們要移動他們的位置,只需分離附加即可,而這些系統(tǒng)數(shù)據(jù)庫沒有分離的選項(xiàng),那要怎么移動他們呢?2016-05-05