根据条件将 1 个表分成两个表,然后 JOIN 两个表保持 NULL 而不是重复

问题描述 投票:0回答:1

我有一个“客户历史记录”表,其中包含不同类型的条目。 我想要获取类型 = '电子邮件' 且来源 = '外部' 或来源 = '客户' 的条目。

所以我会得到:

身份证 类型 来源 日期
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 中的不同帖子,但我无法使其工作。

sql t-sql join
1个回答
0
投票

这可以使用窗口函数

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

演示在这里

© www.soinside.com 2019 - 2024. All rights reserved.