Can I use non-aggregate columns with group by?

前端 未结 6 819
不思量自难忘°
不思量自难忘° 2020-12-09 09:24

You cannot (should not) put non-aggregates in the SELECT line of a GROUP BY query.

I would however like access the one of the non-aggregate

6条回答
  •  萌比男神i
    2020-12-09 10:06

    PostgesSQL's DISTINCT ON will be useful here.

    SELECT DISTINCT ON (kind) kind, id, age 
    FROM stuff
    ORDER BY kind, age DESC;
    

    This groups by kind and returns the first row in the ordered format. As we have ordered by age in descending order, we will get the row with max age for kind.

    P.S. columns in DISTINCT ON should appear first in order by

提交回复
热议问题