Aggregating in SQL - Multiple Criteria

末鹿安然 提交于 2019-12-08 13:26:47

问题


This is a follow-up question to Aggregating in SQL

I have a table below.

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

Grouped by Conversion_Date and User_Name, what is the sum of the Touch_Count looking back 30 days from the Conversion Date but at the same time keeping the Last_Date_Touch within that 30 day window of the Conversion_Date.

For example, if I look back 30 days from the Conversion_Date = 7/19/2017, I cannot just take the sum of the Touch_Count for the 30 day window like below because it will include the first row which has a Last_Date_Touch out of the 30 day window of the conversion date.

This was the attempt, but I don't think it takes into account the Last_Date_Touch being in that 30 day window.

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

Thanks!

来源:https://stackoverflow.com/questions/46180356/aggregating-in-sql-multiple-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!