Issue: I have a query that tracks monthly signups and savers for the current year. However, January’s total signups and savers continue to update when February starts. I want January's data to freeze once February begins, and February’s data to be calculated independently. The goal is to have frozen totals for past months and current month values updating automatically.
Query:
WITH FirstInflowData AS (
SELECT
CreatedBy AS UserId,
MIN(CreatedOn) AS FirstInflowDate
FROM
[Database].wallettopuplog
WHERE
Status = 1
AND IsCredited = 1
AND Amount > 0
GROUP BY
CreatedBy
)
SELECT
DATE_FORMAT(
MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL (m.mn - 1) MONTH,
'%M'
) AS MonthName,
-- Total signups up until the cutoff date (January stops updating once we reach February)
(SELECT COUNT(*)
FROM [Database].customer
WHERE CreatedOn <=
CASE
WHEN m.mn < MONTH(CURDATE()) THEN
LAST_DAY(MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL (m.mn - 1) MONTH)
ELSE CURDATE() -- For the current month (February), it will use today as the cutoff
END
) AS TotalSignups,
-- Signups that occurred only in the current month (Exclusive to that month)
(SELECT COUNT(*)
FROM [Database].customer
WHERE YEAR(CreatedOn) = YEAR(CURDATE())
AND MONTH(CreatedOn) = m.mn) AS MonthlySignups,
-- Total savers up until the cutoff date (Frozen for previous months)
(SELECT COUNT(DISTINCT w.CreatedBy)
FROM [Database].wallettopuplog w
JOIN [Database].customer c ON c.Id = w.CreatedBy
WHERE c.Status = 1 -- Active customers only
AND w.Status = 1 -- Successful transactions only
AND w.IsCredited = 1 -- Credited transactions only
AND w.Amount > 0 -- Only positive amounts
AND w.CreatedOn <=
CASE
WHEN m.mn < MONTH(CURDATE()) THEN
LAST_DAY(MAKEDATE(YEAR(CURDATE()), 1) + INTERVAL (m.mn - 1) MONTH)
ELSE CURDATE() -- For the current month (February), it will use today as the cutoff
END
) AS TotalSavers,
-- Savers whose first inflow occurred in the given month (For the current month only)
(SELECT COUNT(UserId)
FROM FirstInflowData
WHERE YEAR(FirstInflowDate) = YEAR(CURDATE())
AND MONTH(FirstInflowDate) = m.mn
) AS MonthlySavers
FROM
(
SELECT 1 AS mn UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4
UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8
UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12
) AS m
WHERE m.mn <= MONTH(CURDATE()) -- Limits the query to the current month only
ORDER BY m.mn;
What’s Happening: Image of the table January data is not freezing when February starts, causing both months to show identical totals for signups and savers. I need January totals to stop updating once February begins and for February to show its own data, not cumulative totals. Any advice on how to make this work as expected would be greatly appreciated!