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
2
Answers
I would create a table
wktable
that looks like so (for the last 5 weeks of last year):To get there, find a way to create 365 consecutive integers, make all the dates of 2022 out of that, and group them by year-week.
This is an example:
With that table, go:
I first build a list with the records, their open count, and the closed count
After that it’s just adding a GROUP BY:
see: DBFIDDLE
NOTE: Because I use random times, the results will change when re-run. A sample output is: