Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT TOP 2 MAX Value Group By SQL

I have the following table:

-----------------------------------------
xDate        xItem       xCount
-----------------------------------------
2018-01-01   A           100
2018-01-01   B           200
2018-01-01   D           500
2018-01-02   C           200
2018-01-02   E           800

I want to select TOP 2 value for each date on the MAX value of xCount field. So, the result should be:

-----------------------------------------
xDate        xItem      xCount
-----------------------------------------
2018-01-01   D          500
2018-01-01   B          200
2018-01-02   E          800
2018-01-02   C          200

Does anyone have an idea for this case?
Cheers,

like image 514
Haminteu Avatar asked Jan 26 '23 23:01

Haminteu


1 Answers

You can try to use RANK window function, if there more the two row have same xCount then you want to get them all.

You can try to use dense_rank instead of RANK

SELECT xDate,xItem,xCount
FROM (
    SELECT *,RANK() OVER(PARTITION BY xDate ORDER BY xCount DESC) rn
    FROM T
) t1
WHERE t1.rn <= 2
like image 103
D-Shih Avatar answered Feb 04 '23 07:02

D-Shih