Monday, April 9, 2012

Difference beween Rank(), Dense_Rank(), Row number()

DECLARE @OrderRanking AS TABLE
(
OrderID INT IDENTITY(1,1) NOT NULL,
CustomerID INT,
OrderTotal decimal(15,2)
)

INSERT into @OrderRanking (CustomerID, OrderTotal)
SELECT 1, 1000
UNION ALL
SELECT 1, 500
UNION ALL
SELECT 1, 650
UNION ALL
SELECT 1, 650
UNION ALL
SELECT 1, 3000
UNION ALL
SELECT 2, 1000
UNION ALL
SELECT 2, 2000
UNION ALL
SELECT 2, 500
UNION ALL
SELECT 2, 500
UNION ALL
SELECT 3, 500
UNION ALL
SELECT 3, 20

SELECT * FROM @OrderRanking

SELECT *,
ROW_NUMBER() OVER (ORDER BY OrderTotal DESC) AS RN,
ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderTotal DESC) AS RNP,
RANK() OVER (ORDER BY OrderTotal DESC) AS R,
RANK() OVER (PARTITION BY CustomerID ORDER BY OrderTotal DESC) AS RP,
DENSE_RANK() OVER (ORDER BY OrderTotal DESC) AS DR,
DENSE_RANK() OVER (PARTITION BY CustomerID ORDER BY OrderTotal DESC) AS DRP
FROM @OrderRanking