SQL Get Other Rows From Aggregate Function

前端 未结 3 1459
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 09:42

I have an aggregate function that does a group by (col A). It selects the maximum value from a set of columns(col B), but I also want to return another value from a column

3条回答
  •  半阙折子戏
    2020-12-19 10:20

    since you haven't mention the RDBMS you are using, use this query which works on almost all RDBMS

    SELECT  a.*
    FROM    tableName a
            INNER JOIN
            (
                SELECT  A, MAX(b) max_B
                FROM    tableName
                WHERE   b > 50
                GROUP   BY A
            ) b ON a.A = b.A   AND
                a.B = b.max_B
    
    • SQLFiddle Demo

    But if your RDBMS support window functions, you can use DENSE_RANK()

    SELECT  A, B, C
    FROM    
            (
                SELECT  A, B, C,
                        DENSE_RANK() OVER (PARTITION A ORDER BY B DESC) rn
                FROM    tableName
                WHERE   b > 50
                GROUP   BY      
            ) a
    WHERE   rn = 1
    

提交回复
热议问题