Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Sort By a Column and group by another column simultaneously

Raw Table : Jobs

| Amount |  Name |
        3    Raj
        1    Nish
        15   Nish
        10   Nish
        8    Krish
        22   Rahul
        5    Raj
        50   Raj

Required result format

 | Amount |  Name |
        50    Raj
         5    Raj
         3    Raj
        22    Rahul
        15    Nish
        10    Nish
         1    Nish
         8    Krish

The logic i am applying is sort the amount column and get the max amount i.e (50) and get the other transaction of that person (Raj) and continue to search the second max item excluding the already selected person detail(excluding Raj).

Please help me with this

I Tried order by first "Amt" and then by "name" but it will not yield result as expected

like image 428
Nishanth Avatar asked Jun 27 '26 06:06

Nishanth


1 Answers

This statement will give each name with its maximum amount.

select name, max(amount) as max_amt
from jobs
group by name
order by max_amt desc;

Raj    50
Nish   25
Rahul  22
Krish   8

Sorting on max_amt desc gives us the groups in the right order. Now all we need to do is join that to the "jobs" table, and sort the result by the two numerical columns.

I used a CTE to simplify things a bit.

with max_amounts as (
  select name, max(amount) as max_amt
  from jobs
  group by name
)
select t1.*, t2.max_amt from jobs t1
inner join max_amounts t2 
        on t2.name = t1.name
order by max_amt desc, amount desc;

In standard SQL, I think you can just remove max_amt from the outer SELECT clause, and still use order by max_amt desc.

like image 177
Mike Sherrill 'Cat Recall' Avatar answered Jun 29 '26 20:06

Mike Sherrill 'Cat Recall'