I am trying to count 2 different date columns on a monthly interval by using a number table:
numbers table:
num |
---|
0 |
1 |
2 |
3 |
Originating Table (Example):
Gender | Subscription_Date | Cancel_Date |
---|---|---|
male | 2023-01-01 | 2023-05-01 |
male | 2023-01-05 | 2023-01-08 |
male | 2023-01-05 | 2023-03-09 |
male | 2023-02-01 | 2023-04-08 |
female | 2023-01-05 | 2023-04-08 |
female | 2023-01-07 | NULL |
Final output should be like:
ReportMonth | Gender | Subscriptions | Cancellations |
---|---|---|---|
2023-01-01 | male | 3 | 1 |
2023-01-01 | female | 2 | 0 |
2023-02-01 | male | 1 | 0 |
2023-02-01 | female | 0 | 0 |
2023-03-01 | male | 0 | 1 |
2023-03-01 | female | 0 | 0 |
2023-04-01 | male | 0 | 1 |
2023-04-01 | female | 0 | 1 |
2023-05-01 | male | 0 | 0 |
2023-05-01 | female | 1 | 0 |
First attempt:
-- first day of the current month, one year ago
DECLARE @StartDate date = DATEADD(year,-1,DATEADD(month,datediff(month,0,getdate()),0))
-- Start from StartDate, showing results for Subscriptions for each month
SELECT
@StartDate AS StartDate, Numbers.Num, DATEADD(month, Numbers.Num, @StartDate) AS ReportMonth
,S.Gender
,COUNT(S.SubscriptionDate) AS Subscriptions
FROM Numbers
JOIN
OriginatingTable AS S ON DATEADD(month, Numbers.Num, @StartDate) = DATEADD(MONTH, DATEDIFF(MONTH, 0, S.SubscriptionDate), 0)
WHERE (Numbers.Num <= DATEDIFF(month, @StartDate, GETDATE()))
GROUP BY Numbers.Num, DATEADD(month, Numbers.Num, @StartDate), DATEADD(MONTH, DATEDIFF(MONTH, 0, S.Subscription_Date), 0), S.Gender
ORDER BY Numbers.Num
This works, but I fail to integrate the second column "Cancellations".