【发布时间】:2021-11-06 08:57:10
【问题描述】:
我需要编写一个查询来回答以下问题:
“提供 2018-2020 年期间但未在 2021 年预订的客户的报告”
我生成了以下查询以按年份分离出如下所示的数据,每个表代表每年的客户预订量。
按年份获取客户预订:
with active_2018 as
(
select c.id, c.email, c.telephone
from customer c
join booking b on b.customer_id = c.id
where to_char(b.date_created, 'YYYY') = '2018'
group by 1, 2, 3
),
active_2019 as
(
select c.id, c.email, c.telephone
from customer c
join booking b on b.customer_id = c.id
where to_char(b.date_created, 'YYYY') = '2019'
group by 1, 2, 3
),
active_2020 as
(
select c.id, c.email, c.telephone
from customer c
join booking b on b.customer_id = c.id
where to_char(b.date_created, 'YYYY') = '2020'
group by 1, 2, 3
),
active_2021 as
(
select c.id, c.email, c.telephone
from customer c
join booking b on b.customer_id = c.id
where to_char(b.date_created, 'YYYY') = '2021'
group by 1, 2, 3
)
我意识到以下尝试是错误的,但到目前为止这是我最好的尝试,我认为这个查询是说显示在 2018 年和 2019 年和 2020 年而不是在 2021 年预订的客户预订。这是错误的,因为我实际上需要那些已在 2018 年或 2019 年或 2020 年预订,但未在 2021 年预订。
尝试 #1 - 失败:
select distinct(a.id), a.email, a.telephone
from active_2018 a on a.id = a.id
join active_2019 b on a.id = b.id
join active_2020 c on a.id = c.id
where a.id not in (select id from active_2021)
【问题讨论】:
标签: sql amazon-redshift