Skip to content
Advertisement

get 2nd highest sum in mysql

i have table emp :

emp_id quantity 
1001   21
1001   10
1002   3
1002   5
1004   4
1004   5 
1004   8

i want to get the id having 2nd highest sum

so expected output is
1004 17

let me know how can this be done?

SELECT *,
       ROW_NUMBER() OVER(ORDER BY sum_col DESC) as rownum
FROM(
    select order_id,
           sum(quantity) as sum_col
    from order1 
    group by order_id) t
    WHERE t.rownum=2

my query is giving error at line: WHERE t.rownum=2 However if i remove this line it works fine. Let me know how can i put this condition

Advertisement

Answer

WITH cte AS ( SELECT emp_id, 
                     SUM(quantity) `sum`, 
                     DENSE_RANK() OVER (ORDER BY SUM(quantity) DESC) `rank`
              FROM test
              GROUP BY 1 )
SELECT emp_id, `sum`
FROM cte
WHERE `rank` = 2;

DENSE_RANK() needed (not RANK()) because if, for example, there is 2 rows with highest sum then they’ll have RANK and DENSE_RANK equal to 1, but for the next sum value DENSE_RANK will be 2 whereas single RANK will be 3.

fiddle

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement