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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With