PostgreSQL,聚合和组合
PostgreSQL, aggregate and combine
我在 PostgreSQL 中有一个 table:
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
或类似的?
您可以使用条件聚合:
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
您可以使用过滤聚合:
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
我在 PostgreSQL 中有一个 table:
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
或类似的?
您可以使用条件聚合:
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
您可以使用过滤聚合:
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