I have the following two tables courses
and enrollments
in my PieCloudDB Database:
course_id | course_name |
---|---|
1 | Deep Learning |
2 | Data Science |
3 | C++ |
enrollment_id | course_id | customer_id | enrollment_date |
---|---|---|---|
101 | 1 | 201 | 2024-01-15 |
102 | 1 | 202 | 2024-01-20 |
103 | 2 | 203 | 2024-02-01 |
104 | 3 | 204 | 2024-02-15 |
105 | 1 | 205 | 2024-03-01 |
106 | 2 | 206 | 2024-03-10 |
107 | 3 | 207 | 2024-03-20 |
I now want to query the number of registrations for each course per month and the cumulative number of registrations for the course.
Below is my query:
SELECT
EXTRACT(YEAR FROM e.enrollment_date) AS year,
EXTRACT(MONTH FROM e.enrollment_date) AS month,
c.course_name,
COUNT(DISTINCT e.customer_id) AS monthly_registrations,
SUM(COUNT(DISTINCT e.customer_id)) OVER (
PARTITION BY e.course_id
ORDER BY EXTRACT(YEAR FROM e.enrollment_date), EXTRACT(MONTH FROM e.enrollment_date)
) AS cumulative_registrations
FROM
enrollments e
JOIN
courses c ON e.course_id = c.course_id
GROUP BY
e.course_id,
c.course_name,
year,
month
ORDER BY
year,
month,
c.course_name;
Then I got the results:
year | month | course_name | monthly_registrations | cumulative_registrations |
---|---|---|---|---|
2024 | 1 | Deep Learning | 2 | 2 |
2024 | 2 | C++ | 1 | 1 |
2024 | 2 | Data Science | 1 | 1 |
2024 | 3 | C++ | 1 | 2 |
2024 | 3 | Data Science | 1 | 2 |
2024 | 3 | Deep Learning | 1 | 3 |
Now there is a problem. I want to get more complete information. When the number of registrations for a certain course in a certain month is 0, it also need to be outputted.
For example, for the above data I would like to get a result like this:
year | month | course_name | monthly_registrations | cumulative_registrations |
---|---|---|---|---|
2024 | 1 | C++ | 0 | 0 |
2024 | 1 | Data Science | 0 | 0 |
2024 | 1 | Deep Learning | 2 | 2 |
2024 | 2 | C++ | 1 | 1 |
2024 | 2 | Data Science | 1 | 1 |
2024 | 2 | Deep Learning | 0 | 2 |
2024 | 3 | C++ | 1 | 2 |
2024 | 3 | Data Science | 1 | 2 |
2024 | 3 | Deep Learning | 1 | 3 |
I don’t know how to do it, can anyone help me?(If you don’t know PieCloudDB, you can use PostgreSQL instead, thanks)