我有一个“客户历史记录”表,其中包含不同类型的条目。 我想要获取类型 = '电子邮件' 且来源 = '外部' 或来源 = '客户' 的条目。
所以我会得到:
身份证 | 类型 | 来源 | 日期 |
---|---|---|---|
11 | 电子邮箱 | 外部 | 12/02/24 |
11 | 电子邮箱 | 外部 | 13/02/24 |
11 | 电子邮箱 | 客户 | 10/02/24 |
我的主要目标是修改此结果以获得:
身份证 | 外部来源日期 | 客户来源日期 |
---|---|---|
11 | 12/02/24 | 10/02/24 |
11 | 13/02/24 | 空 |
我只需要日期列,一列仅从来源为“外部”的“电子邮件”条目中获取日期,另一列从来源为“客户”时获取日期
我尝试了所有不同的 JOIN,我应用了 WHERE 条件,向 JOIN 本身的 ON 子句添加条件,阅读此处和 Google 中的不同帖子,但我无法使其工作。
这可以使用窗口函数
row_number()
来完成,如下所示:
select Id,
max(case when Source = 'External' then Date end) as 'External source Date',
max(case when Source = 'Customer' then Date end) as 'Customer source Date'
from (
select *, row_number() over (partition by Id, Type, Source order by Date) as rn
from mytable
) as s
group by Id, Type, rn;
结果:
Id External source Date Customer source Date
11 2024-02-12 2024-02-10
11 2024-02-13 null