Select multiple (non-aggregate function) columns with GROUP BY

后端 未结 4 1215
醉酒成梦
醉酒成梦 2020-12-14 09:59

I am trying to select the max value from one column, while grouping by another non-unique id column which has multiple duplicate values. The original database looks somethin

4条回答
  •  清歌不尽
    2020-12-14 10:28

    You have yourself a greatest-n-per-group problem. This is one of the possible solutions:

    select c.mukey, c.comppct_r, c.name, c.type
    from c yt
    inner join(
        select c.mukey, max(c.comppct_r) comppct_r
        from c
        group by c.mukey
    ) ss on c.mukey = ss.mukey and c.comppct_r= ss.comppct_r
    

    Another possible approach, same output:

    select c1.*
    from c c1
    left outer join c c2
    on (c1.mukey = c2.mukey and c1.comppct_r < c2.comppct_r)
    where c2.mukey is null;
    

    There's a comprehensive and explanatory answer on the topic here: SQL Select only rows with Max Value on a Column

提交回复
热议问题