问题
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