我有一个原始数据,每个类别有多个日期,我使用代码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
我尝试通过使用distinct
或group 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
, date_entered
, category
但它将继续返回多行,每行计算每个类别的最早日期。我还尝试在select distinct id, date_entered, date_referral, date_reply, date_final from table
的代码之后创建cte,但它仍然返回多行。。
如何组合这些行并使其返回一行?
您不应该按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