I have a table with created_at
and deleted_at
timestamps. I need to know, for each week, how many records existed at any point that week:
week | records |
---|---|
2022-01 | 4 |
2022-02 | 5 |
... | ... |
Essentially, records that were created before the end of the week and deleted after the beginning of the week.
I've tried various variations of the following but it's under-reporting and I can't work out why:
SELECT
DATE_FORMAT(created_at, '%Y-%U') AS week,
COUNT(*)
FROM records
WHERE
deleted_at > DATE_SUB(deleted_at, INTERVAL (WEEKDAY(deleted_at)+1) DAY)
AND created_at < DATE_ADD(created_at, INTERVAL 7 - WEEKDAY(created_at) DAY)
GROUP BY week
ORDER BY week
Any help would be massively appreciated!
Update: I found How to populate a table with a range of dates? and propose this question be closed