假设我们有一个简单的表users
:
id | name | company | other columns.......
----+------+---------+-------------------------
1 | A | A1
2 | A | A2
3 | B | B1
4 | C | C1
5 | C | C2
6 | C | C3
....
我想按名称分组,并为id
和company
选择了最新的值。我期望的结果是三列表:
id | name | company |
----+------+---------+
2 | A | A2
3 | B | B1
6 | C | C3
....
我正在尝试使用GROUP_BY
,但不知道如何包含company
列:
SELECT
max(id),
name,
? # I don't know how to include company
FROM users
GROUP_BY name
有人有更好的主意吗?
使用distinct on
:
select distinct on (name) u.*
from users u
order by name, id desc;
distinct on
是一个非常方便的Postgres扩展。它返回一组行中的第一行。";分组";基于CCD_ 8之后的列。排序基于order by
子句。
有另外两种常见的方法来解决这个问题。一种方法使用窗口函数:
select u.*
from (select u.*,
row_number() over (partition by name order by id desc) as seqnum
from users u
) u
where seqnum = 1;
或者一个相关的子查询:
select u.*
from users u
where u.id = (select max(u2.id) from users u2 where u2.name -= u.name);
甚至还有一个";聪明的";使用CCD_ 10。Postgres没有;第一个";或";最后一个";聚合函数。但是你可以使用数组:
select name, max(id),
(array_agg(company order by id desc))[1] as country
from users u
group by name;