Search code examples
sqlsql-serverrankingdense-rank

How to make Ranking based on Year and Month?


I am trying to put Rank based on Year and Month. I have records like

Products

ProdID  Years  Months  Quantity
--------------------------------
1652    2018    10         2    
1010    2018    9          2    
2236    2018    10         2    
2236    2018    10         2    
1445    2019    5          2    
1789    2019    12         2    
1232    2018    12         2    

I tried the below Query

SELECT
    ProdID, Years, Months, Quantity,
    DENSE_RANK()OVER (Partition By Years Order By Months) Ranks
FROM Products

Obviously, the result will be

ProdID  Years  Months  Quantity   Ranks
---------------------------------------
1010    2018    9          2       1
1652    2018    10         2       2 
2236    2018    10         2       2
2236    2018    10         2       2
1232    2018    12         2       3
1445    2019    5          2       1
1789    2019    12         2       2

Expect

ProdID  Years  Months  Quantity   Ranks
---------------------------------------
1010    2018    9          2       1
1652    2018    10         2       2 
2236    2018    10         2       2
2236    2018    10         2       2
1232    2018    12         2       3
1232    2018    12         2       3
1445    2019    5          2       4
1789    2019    12         2       5

Solution

  • You need to remove the partition by clause from your query. Just use order by clause.

    SELECT ProdID, Years, Months, Quantity,
    DENSE_RANK()OVER (Order By Years, Months) Ranks
    FROM Products