ROW_NUMBER() :給整體結果集中的行標明序號,依次加1
RANK():先分組(也可以不分組),然後每組的行各自標明序號,依次加1,假如該組中排序列的值相同,就會有一些行擁有相同的序號,但接下來的行的序號會不連貫。比如有兩行的序號是並列第1,則第3行的序號是3而不是2。
DENSE_RANK():接近RANK(),區別是雖然也有相同序號,但排名是連貫的。比如有兩行的序號是並列第1,則第3行的序號是2而不是3。
NTILE(n):將結果集分成n等份,然後每等份裡面的行標明序號,同一份裡的序號都是相同的(比如說,分成4等份,份1裡所有行的序號都是1,份2裡所有行的序號都是2,以此類推);或者先分組,然後每組分成n等份,等份裡面再標明序號。(什麼情況下會用到呢?)
USE AdventureWorks;
GO
SELECT c.FirstName, c.LastName
,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS 'Row Number'
,RANK() OVER (ORDER BY a.PostalCode) AS 'Rank'
,DENSE_RANK() OVER (ORDER BY a.PostalCode) AS 'Dense Rank'
,NTILE(4) OVER (ORDER BY a.PostalCode) AS 'Quartile'
,s.SalesYTD, a.PostalCode
FROM Sales.SalesPerson s
INNER JOIN Person.Contact c ON s.SalesPersonID = c.ContactID
INNER JOIN Person.Address a ON a.AddressID = c.ContactID
WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0;
FirstName |
LastName |
Row Number |
Rank |
Dense Rank |
Quartile |
SalesYTD |
PostalCode |
Maciej |
Dusza |
1 |
1 |
1 |
1 |
4557045 |
98027 |
Shelley |
Dyck |
2 |
1 |
1 |
1 |
5200475 |
98027 |
Linda |
Ecoffey |
3 |
1 |
1 |
1 |
3857164 |
98027 |
Carla |
Eldridge |
4 |
1 |
1 |
1 |
1764939 |
98027 |
Carol |
Elliott |
5 |
1 |
1 |
2 |
2811013 |
98027 |
Jauna |
Elson |
6 |
6 |
2 |
2 |
3018725 |
98055 |
Michael |
Emanuel |
7 |
6 |
2 |
2 |
3189356 |
98055 |
Terry |
Eminhizer |
8 |
6 |
2 |
3 |
3587378 |
98055 |
Gail |
Erickson |
9 |
6 |
2 |
3 |
5015682 |
98055 |
Mark |
Erickson |
10 |
6 |
2 |
3 |
3827950 |
98055 |
Martha |
Espinoza |
11 |
6 |
2 |
4 |
1931620 |
98055 |
Janeth |
Esteves |
12 |
6 |
2 |
4 |
2241204 |
98055 |
Twanna |
Evans |
13 |
6 |
2 |
4 |
1758386 |
98055 |