在SQL中聚合 - 多个标准

时间:2017-09-12 15:29:45

标签: sql group-by aggregate amazon-redshift

这是Aggregating in SQL

的后续问题

我有一张桌子。

Conversion_Date     User_Name     Last_Date_Touch     Touch_Count
      7/15/2017             A           6/17/2017               1
      7/16/2017             B           6/24/2017               2
      7/19/2017             A           6/20/2017               1
      7/19/2017             C           6/29/2017               1

Conversion_DateUser_Name分组,Touch_Count回顾Conversion Date 30天后的总和是多少,但同时保留Last_Date_Touch在Conversion_Date的30天窗口内

例如,如果我从Conversion_Date = 7/19/2017回顾30天,我不能像下面那样在30天窗口中获取Touch_Count的总和,因为它将包含具有Last_Date_Touch的第一行转换日期的30天窗口。

这是尝试,但我认为它不会考虑在30天窗口中的Last_Date_Touch

select
     a.User_Name
    ,a.Conversion_Date
    ,sum(b.Touch_Count) as SumOver30Days
from
    SomeTable a
    left join
        SomeTable b on
        b.User_Name = a.User_name
        and cast(b.Conversion_Date as date) <= cast(a.Conversion_Date as date) 
        and cast(b.Conversion_Date as date) >= cast(dateadd(day,-30,a.Conversion_Date) as date)
group by a.User_Name, a.Conversion_Date

谢谢!

0 个答案:

没有答案