Search code examples
sqlsql-order-by

Create an order column based on count (sql)


I have a dataset like this :

Groupe | Count     
A      | 22    
B      | 12    
A      | 10    
B      | 16

I want to obtain this :

Groupe | Count | Total | Order    
A      | 22    | 32    | 1    
B      | 12    | 28    | 2
A      | 10    | 32    | 1    
B      | 16    | 28    | 2

So I did this for Total column :

sum("Count") OVER (PARTITION BY "Group")

It's ok but for order :

ROW_NUMBER() OVER (ORDER BY "Total" DESC)

But I get :

Groupe | Count | Total | Order    
A      | 22    | 32    | 1    
B      | 12    | 28    | 4    
A      | 10    | 32    | 2    
B      | 16    | 28    | 3

Do you know how to create the order column based on total column and in case of equality put the same order to obtain this :

Groupe | Count | Total | Order    
A      | 22    | 32    | 1    
B      | 12    | 28    | 2    
A      | 10    | 32    | 1   
B      | 16    | 28    | 2

Solution

  • select 
        *,
        DENSE_RANK() over(order by Total desc ) as "Order" 
    from 
    (
        select 
            Groupe, 
            count, 
            sum(count) over(partition by Groupe)   as Total
        from TableName 
    ) a