How to select records with maximum values in two columns?

后端 未结 2 813
生来不讨喜
生来不讨喜 2020-11-30 13:41

It was hard to come up with an understandable title for this question. I\'ll try to explain with an example.

First I had a simple table INFO in Oracle

相关标签:
2条回答
  • 2020-11-30 14:00

    Analytic functions are your friend:

    SELECT   MAX( year    ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS year,
             MAX( quarter ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS quarter,
             MAX( message ) KEEP ( DENSE_RANK LAST ORDER BY year ASC, quarter ASC, message ASC ) AS message,
             type
    FROM     info
    GROUP BY type;
    

    SQLFIDDLE

    0 讨论(0)
  • 2020-11-30 14:16

    Give this a shot:

    SELECT i.year, i.quarter, i.type, i.message
    FROM INFO i
    JOIN INFO iy
        ON i.type = iy.type
    JOIN INFO iq
        ON iq.type = iy.type    
    WHERE i.type IN (1,2)   
    GROUP BY i.year, i.quarter, i.type, i.message   
    HAVING i.year = MAX(iy.year) AND i.quarter = MAX(iq.quarter)
    
    0 讨论(0)
提交回复
热议问题