将多行数据合并为每个 id 的一行

问题描述

我有一个每个类别有多个日期的原始数据,我使用代码 case when category = 'referral' then min(date) end as date_referral 来获取每个 id 的每个类别的最早日期。

但是,它不会按行返回数据,而是按类别创建行,如下所示:

id    date_entered      date_referral      date_reply        date_final
-------------------------------------------------------------------------
1      2020-12-20           null              null              null 
1      2020-12-20         2020-12-21          null              null 
1      2020-12-20           null            2020-12-21          null 
1      2020-12-20           null              null            2020-12-24

我尝试通过使用 distinctgroup by(单独和一起)强制执行单行:

select distinct id,date_entered,case when category = 'referral' then min(date) end as date_referral,case when category = 'reply' then min(date) end as date_reply,case when category = 'final' then min(date) end as date_final

from data
group by id,category

但它会不断返回多行,每行计算每个类别的最早日期。我也尝试在此代码之后创建 cte 到 select distinct id,date_referral,date_reply,date_final from table 但它仍然返回多行..

如何组合这些行并使其返回一行?

解决方法

您不应按 category 分组。
像这样使用条件聚合:

select id,date_entered,min(case when category = 'referral' then date end) as date_referral,min(case when category = 'reply' then date end) as date_reply,min(case when category = 'final' then date end) as date_final
from data
group by id,date_entered

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...