Ranking Functions & Aggregate Functions & Analytic Functions
- Ranking window functions
- Row_Number()
- Rank()
- Dense_Rank()
- Ntile()
- Aggregate window functions
MIN
, MAX
, AVG
, SUM
COUNT
, COUNT_BIG
- CHECKSUM_AGG
STDEV
, STDEVP
, VAR
, VARP
- Analytic window functions
LAG
, LEAD
FIRST_VALUE
, LAST_VALUE
PERCENT_RANK
, PERCENTILE_CONT
, PERCENTILE_DISC
, CUME_DIST
MIN
,MAX
,AVG
,SUM
COUNT
,COUNT_BIG
- CHECKSUM_AGG
STDEV
,STDEVP
,VAR
,VARP
LAG
,LEAD
FIRST_VALUE
,LAST_VALUE
PERCENT_RANK
,PERCENTILE_CONT
,PERCENTILE_DISC
,CUME_DIST
Ranking Functions
use AdventureWorksDW
go
SELECT *,
ROW_NUMBER() OVER(ORDER BY salesreasonreasontype DESC) AS RowNumber,
RANK() OVER(ORDER BY salesreasonreasontype DESC) AS BasicRank,
DENSE_RANK() OVER(ORDER BY salesreasonreasontype DESC) AS DenseRank,
NTILE(3) OVER(ORDER BY salesreasonreasontype DESC) AS NTileRank
FROM
DimSalesReason
Aggregate Functions
use AdventureWorksDW
go
SELECT
title,departmentname,
COUNT(baserate) OVER(PARTITION BY departmentname) AS CountryCount,
SUM(baserate) OVER(PARTITION BY departmentname) AS TotalSales,
AVG(baserate) OVER(PARTITION BY departmentname) AS AverageSales
FROM
DimEmployee
ORDER BY
title,departmentname DESC;
RESULT:
Analytic Functions
SELECT
SalesGroup,
Country,
AnnualSales,
FIRST_VALUE(AnnualSales) OVER(PARTITION BY SalesGroup
ORDER BY AnnualSales DESC) AS HighestSales,
LAST_VALUE(AnnualSales) OVER(PARTITION BY SalesGroup
ORDER BY AnnualSales DESC) AS LowestSales
FROM
RegionalSales;
OUTPUT:
SalesGroup
|
Country
|
AnnualSales
|
HighestSales
|
LowestSales
|
Europe
|
United Kingdom
|
32000
|
32000
|
32000
|
Europe
|
Germany
|
22000
|
32000
|
22000
|
Europe
|
France
|
19000
|
32000
|
19000
|
Europe
|
Italy
|
18000
|
32000
|
18000
|
Europe
|
Greece
|
16000
|
32000
|
16000
|
Europe
|
Spain
|
16000
|
32000
|
16000
|
North America
|
Canada
|
32000
|
32000
|
32000
|
North America
|
Mexico
|
28000
|
32000
|
28000
|
North America
|
United States
|
22000
|
32000
|
22000
|
Pacific
|
China
|
28000
|
28000
|
28000
|
Pacific
|
Japan
|
22000
|
28000
|
22000
|
Pacific
|
Singapore
|
21000
|
28000
|
21000
|
Pacific
|
Malaysia
|
19000
|
28000
|
19000
|
Pacific
|
Australia
|
18000
|
28000
|
18000
|
Pacific
|
New Zealand
|
18000
|
28000
|
18000
|
Pacific
|
Thailand
|
17000
|
28000
|
17000
|