Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Rank a Partition in T-SQL

I want to give each combination of CardId and InvoiceNo a Number/Rank for the below data

;WITH Test (CardId,InvoiceNo,Category,Amount) as 
(
    SELECT '1001','3001','Fees',30
    UNION ALL   SELECT '1001','3001','Non-Fees',45
    UNION ALL   SELECT '1001','3001','Service Fees',55
    UNION ALL   SELECT '1002','3002','Fees',10
    UNION ALL   SELECT '1002','3002','Non-Fees',25
    UNION ALL   SELECT '1002','3002','Service Fees',10
    UNION ALL   SELECT '1003','3010','Fees',45
    UNION ALL   SELECT '1003','3010','Non-Fees',70


)

Like this

CardId  InvoiceNo   Amount  Rank
1001    3001         30     1
1001    3001         45     1
1001    3001         55     1
1002    3002         10     2
1002    3002         25     2
1002    3002         10     2
1003    3010         45     3
1003    3010         70     3

I tried the below query with both Row_number() and Rank() but is not giving me the desired result. The rank() is ranking all the rows as 1 and the row_number() is numbering each group with 1,2,3.

SELECT CardId
,InvoiceNo
,Amount
,RANK() OVER (PARTITION BY CardID,InvoiceNo ORDER BY CardId) as RankNo

FROM Test
like image 357
Avinash Avatar asked Jan 27 '26 06:01

Avinash


2 Answers

Remove the partitions. The rank function looks within the partitions where a new partition resets the rankings. Thus it was seeing every record within each partition as tied for 1st. Also, you may want dense_rank().

SELECT CardId
    ,InvoiceNo
    ,Amount
    ,DENSE_RANK() OVER (ORDER BY CardId, InvoiceNo) as RankNo    
FROM Test
ORDER BY CardId, InvoiceNo, Amount

Fiddle:

http://sqlfiddle.com/#!18/0f0c2/7

like image 141
Joel Coehoorn Avatar answered Jan 29 '26 22:01

Joel Coehoorn


Try this. I think this is what you are looking for.

SELECT CardId
    ,InvoiceNo
    ,Amount
    ,DENSE_RANK() OVER (ORDER BY CardId, InvoiceNo) as RankNo

FROM Test
like image 25
SS_DBA Avatar answered Jan 29 '26 21:01

SS_DBA