I have a table that logs website activity with the following Columns and Data
ID Date Source Revenue
1 2013-10-01 A 0
2 2013-10-01 A 0
3 2013-10-01 B 10
1 2013-10-02 A 40
4 2013-10-03 B 0
3 2013-10-03 B 0
4 2013-10-04 A 10
I am trying to create a table that takes each transaction (Revenue > 0) and counts all of the visits by source in individual columns for the last 30 days. It should look something like this.
ID Date Source Revenue Count_A Count_B
3 2013-10-01 B 10 0 1
1 2013-10-02 A 40 2 0
4 2013-10-04 A 10 1 1
I have tried using a subquery for each of these columns, but the Counts are way off and I am not sure why.
Select ID,
Date,
Source,
Revenue,
(SELECT Count(*)
FROM table t2
WHERE t2.Date between t.Date-30 and t.Date and Source = 'A') AS Count_A
(SELECT Count(*)
FROM table t3
WHERE t3.Date between t.Date-30 and t.Date and Source = 'B') AS Count_B
FROM table t
Where Revenue > 0
Order By WMEID
I am using Microsoft SQL Server.