SQL-根据开始日期提取日期范围的数据

时间:2020-09-10 19:44:10

标签: sql datetime sum left-join amazon-redshift

我有下面的SQL查询,该查询可查询过去3个月的帐户收入以及每个帐户的服务开始日期(我通过SQL Workbench使用Amazon Redshift)

select distinct r.account_id, r.account_name, s.start_date
  ,SUM(CASE WHEN r.datekey between '20200601' and '20200630' THEN revenue ELSE 0 END) AS "June 2020" 
  ,SUM(CASE WHEN r.datekey between '20200701' and '20200731' THEN revenue ELSE 0 END) AS "July 2020"
  ,SUM(CASE WHEN r.datekey between '20200801' and '20200831' THEN revenue ELSE 0 END) AS "August 2020"  
from revenues r
join start_dates s on r.account_id = s.account_id
group by r.account_id, r.account_name, s.start_date;

如何修改上面的查询以在每个客户开始日期后的3个月内提取收入,请记住每个客户的3个月范围会有所不同?我曾经尝试使用DATEPART和DATEADD,但没有找到使用这些语句的解决方案。

2 个答案:

答案 0 :(得分:1)

您可以更改加入条件以过滤每个account_id之后的三个月start_date的收入,然后使用条件汇总:

select
    s.account_id,
    sum(case when r.datekey < dateadd(month, 1, s.start_date) then revenue else 0 end) as month1,
    sum(case when r.datekey >= dateadd(month, 1, s.start_date) and r.datekey < dateadd(month, 2, s.start_date) then revenue else 0 end) as month2,
    sum(case when r.datekey >= dateadd(month, 2, s.start_date) then revenue else 0 end) as month3
from start_dates s
left join revenues r
    on  r.account_id = s.account_id
    and r.datekey >= s.start_date
    and r.datekey <  dateadd(month, 3, s.start_date)
group by s.account_id

答案 1 :(得分:1)

在这里,将DATEDIFF与start_date和GETDATE()一起使用

select distinct r.account_id, r.account_name, s.start_date
  ,SUM(CASE WHEN r.datekey between '20200601' and '20200630' THEN revenue ELSE 0 END) AS "June 2020" 
  ,SUM(CASE WHEN r.datekey between '20200701' and '20200731' THEN revenue ELSE 0 END) AS "July 2020"
  ,SUM(CASE WHEN r.datekey between '20200801' and '20200831' THEN revenue ELSE 0 END) AS "August 2020"  
from revenues r
join start_dates s on r.account_id = s.account_id
WHERE DATEDIFF(s.start_date, GETDATE())<=90
group by r.account_id, r.account_name, s.start_date;