I’ve a mysql table with me
Now we want to do some calculations like this
- count date wise for all courses enrolled
- count where course id = 2 for date > start_date AND date < end_date
Expected output where we calculate all courses enrolled
Expected output where we calculate all courses enrolled where course id = 2
expected output where course_id = 2 AND date range is between 2022-11-15 to 2022-11-13
The query which I’ve right now
SELECT COUNT(*), DATE(registered_on)
FROM courses_enrolled
WHERE course_id = 1
GROUP BY DATE(registered_on), course_id
ORDER BY registered_on desc;
2
Answers
You need to use some kind of calendar table approach here:
The calendar table ensures that all dates you want in the output appear. In practice, you may replace the subquery in
d
with a bona-fide table containing all dates of interest. The left join ensures that no dates are dropped which have no matching courses on that day.If you are using MySQL 8 you can use a recursive CTE to create your date range.
For all enrolled courses for given date range –
Note the use of BETWEEN start AND end of day in the join criteria. For a small dataset this offers negligible benefit but on a large dataset it would allow for use of an index on
registered_on
, which could offer significantly improved performance.Or for just the selected course –
Or counting both at the same time –