国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

sqlserver巧用row_number和partition by分組取top數據

2020-10-30 19:08:56
字體:
來源:轉載
供稿:網友
分組取TOP數據是T-SQL中的常用查詢, 如學生信息管理系統中取出每個學科前3名的學生。這種查詢在SQL Server 2005之前,寫起來很繁瑣,需要用到臨時表關聯查詢才能取到。SQL Server 2005后之后,引入了row_number()函數,row_number()函數的分組排序功能使這種操作變得非常簡單。下面是一個簡單示例:
復制代碼 代碼如下:

--1.創建測試表
create table #score
(
name varchar(20),
subject varchar(20),
score int
)
--2.插入測試數據
insert into #score(name,subject,score) values('張三','語文',98)
insert into #score(name,subject,score) values('張三','數學',80)
insert into #score(name,subject,score) values('張三','英語',90)
insert into #score(name,subject,score) values('李四','語文',88)
insert into #score(name,subject,score) values('李四','數學',86)
insert into #score(name,subject,score) values('李四','英語',88)
insert into #score(name,subject,score) values('李明','語文',60)
insert into #score(name,subject,score) values('李明','數學',86)
insert into #score(name,subject,score) values('李明','英語',88)
insert into #score(name,subject,score) values('林風','語文',74)
insert into #score(name,subject,score) values('林風','數學',99)
insert into #score(name,subject,score) values('林風','英語',59)
insert into #score(name,subject,score) values('嚴明','英語',96)
--3.取每個學科的前3名數據
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.刪除臨時表
truncate table #score
drop table #score

語法形式:ROW_NUMBER() OVER(PARTITION BY COL1 ORDER BY COL2)
解釋:根據COL1分組,在分組內部根據 COL2排序,而此函數計算的值就表示每組內部排序后的順序編號(組內連續的唯一的)
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浑源县| 诸城市| 伊金霍洛旗| 长泰县| 高密市| 阿拉善左旗| 吐鲁番市| 和政县| 十堰市| 保康县| 宿迁市| 南城县| 固镇县| 翼城县| 班玛县| 土默特左旗| 民和| 乐陵市| 寻甸| 微山县| 白玉县| 化隆| 房产| 宜丰县| 磐安县| 永州市| 德清县| 岑溪市| 德庆县| 盈江县| 宁强县| 西安市| 垫江县| 杭锦旗| 龙里县| 屏东市| 屏东市| 西畴县| 灵山县| 自治县| 富源县|