I have been searching for this and trying to make this code work for a week now.
My data set tbSubscriptions
has the columns:
Subscription_Date (dd/mm/yyyy hh:mm:ss)
Subscription_Id (char 6)
Subscription_Type (char 1)
To retrieve the number of subscriptions per week I use:
select
datepart(wk,Subscription_Date) as WeekNo,
sum(case when Subscription_Type = 1 then 1 else 0 end) as TotalSubcriptions
from tbSubscriptions
group by datepart(wk,Subscription_Date)
order by 1
This query returns:
WeekNo |Total Subscriptions
21 |12
22 |13
23 |8
24 |18
What I want is a Query that returns:
WeekNo |CumulativeSubscriptions
21 |12
22 |25 (=12+13)
23 |33 (=25+8)
24 |51 (=33+18)
Here is a sample data set creation script:
GO
IF OBJECT_ID('tbSubscriptions') IS NOT NULL
DROP TABLE tbSubscriptions
GO
CREATE TABLE tbSubscriptions (Subscription_Id INT, Subscription_Date datetime, Subscription_Type INT)
GO
INSERT INTO tbSubscriptions (Subscription_Id, Subscription_Date, Subscription_Type)
VALUES
(1, convert(datetime,'01-08-16 00:00:00 AM',5),1),
(2, convert(datetime,'15-08-16 00:00:00 AM',5),1),
(3, convert(datetime,'01-09-16 00:00:00 AM',5),1),
(4, convert(datetime,'09-09-16 00:00:00 AM',5),1),
(5, convert(datetime,'18-09-16 00:00:00 AM',5),0),
(6, convert(datetime,'15-10-16 00:00:00 AM',5),1),
(7, convert(datetime,'22-10-16 00:00:00 AM',5),0),
(8, convert(datetime,'23-10-16 00:00:00 AM',5),0),
(9, convert(datetime,'01-11-16 00:00:00 AM',5),1),
(10, convert(datetime,'02-11-16 00:00:00 AM',5),1),
(11, convert(datetime,'14-11-16 00:00:00 AM',5),0),
(12, convert(datetime,'01-12-16 00:00:00 AM',5),1),
(13, convert(datetime,'02-12-16 00:00:00 AM',5),1),
(14, convert(datetime,'05-12-16 00:00:00 AM',5),1),
(15, convert(datetime,'09-12-16 00:00:00 AM',5),1),
(16, convert(datetime,'10-12-16 00:00:00 AM',5),1),
(17, convert(datetime,'11-12-16 00:00:00 AM',5),1),
(18, convert(datetime,'19-12-16 00:00:00 AM',5),0),
(19, convert(datetime,'25-12-16 00:00:00 AM',5),0),
(20, convert(datetime,'29-12-16 00:00:00 AM',5),0);
GO
I have tried both methods for cumulative sum (Window Functions and Self Joins), but couldn't get to work.
Any help would be much appreciated.
Kind regards, Paulo.