Question

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

Was it helpful?

Solution

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.

OTHER TIPS

create table SORT_AMT_NAME(AMOUNT INT,NAME VARCHAR(20))


INSERT INTO SORT_AMT_NAME Values (22,'Rahul')
INSERT INTO SORT_AMT_NAME Values (8,'Krish')
INSERT INTO SORT_AMT_NAME Values (15,'Nish')
INSERT INTO SORT_AMT_NAME Values (1,'Nish')
INSERT INTO SORT_AMT_NAME Values (10,'Nish')
INSERT INTO SORT_AMT_NAME Values (50,'Raj')
INSERT INTO SORT_AMT_NAME Values (3,'Raj')
INSERT INTO SORT_AMT_NAME Values (5,'Raj')
INSERT INTO SORT_AMT_NAME Values (25,'GS')




SELECT AMOUNT,SORT_AMT_NAME.NAME FROM SORT_AMT_NAME,
(
select MAX(AMOUNT) AS MAX_AMT,NAME,ROW_NUMBER() over (order by MAX(AMOUNT) desc) as Amount_Order
from SORT_AMT_NAME
GROUP BY NAME) x
WHERE X.NAME=SORT_AMT_NAME.nAME
ORDER BY Amount_Order ASC ,AMOUNT DESC,SORT_AMT_NAME.NAME
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top