我在PostgreSQL有一张桌子:
name TEXT,
country_code TEXT
visited TIMESTAMP
我知道country_code
只能是US
,UK
或者CH
。
我想要一个类似于:
name, US-last-visited, UK-last-visited, CH-last-visited
Gregg null 2022-01-02 2001-01-02
Paul 1999-01-10 null 2021-01-03
能不能用GROUP BY
和ARRAY_AGG
或类似的方法来做一些简单的事情?
发布于 2022-05-24 13:41:50
您可以使用条件聚合:
select name
, max(case when country_code = 'US' then visited end) as US_last_visited
, max(case when country_code = 'UK' then visited end) as UK_last_visited
, max(case when country_code = 'CH' then visited end) as CH_last_visited
from t
group by name
发布于 2022-05-24 13:42:39
您可以使用过滤的聚合:
select name,
max(visited) filter (where country_code = 'UK') as uk_last_visited,
max(visited) filter (where country_code = 'US') as us_last_visited,
max(visited) filter (where country_code = 'CH') as ch_last_visited
from the_table
group by name
https://stackoverflow.com/questions/72363967
复制相似问题