首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PostgreSQL,聚合和组合

PostgreSQL,聚合和组合
EN

Stack Overflow用户
提问于 2022-05-24 13:40:02
回答 2查看 37关注 0票数 0

我在PostgreSQL有一张桌子:

代码语言:javascript
运行
复制
name TEXT,
country_code TEXT
visited TIMESTAMP

我知道country_code只能是USUK或者CH

我想要一个类似于:

代码语言:javascript
运行
复制
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 BYARRAY_AGG或类似的方法来做一些简单的事情?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-05-24 13:41:50

您可以使用条件聚合:

代码语言:javascript
运行
复制
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
票数 0
EN

Stack Overflow用户

发布于 2022-05-24 13:42:39

您可以使用过滤的聚合:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72363967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档