sql 分組取最新的資料sqlserver巧用row_number和partition by分組取top資料

來源:互聯網
上載者:User

標籤:log   rom   .net   subject   dem   管理系統   creat   des   學生資訊管理系統   

SQL Server 2005後之後,引入了row_number()函數,row_number()函數的分組排序功能使這種操作變得非常簡單

分組取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排序,而此Function Compute的值就表示每組內部排序後的順序編號(組內連續的唯一的)

 

轉自:http://blog.csdn.net/zengcong2013/article/details/45833363

 

sql 分組取最新的資料sqlserver巧用row_number和partition by分組取top資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.