I'm stuck with this query and I would like to have a hand.
So I have two tables : Course and Absence.
The purpose of my query is to count, for a student, all his courses and absences for each months of the year.
With just the courses, I have this query :
SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month
ORDER BY MONTH(c.date);
The result looks like this :
+-----------+--------+
| month | courses|
+-----------+--------+
| January | 24 |
| February | 20 |
| March | 20 |
| April | 22 |
| May | 23 |
| June | 20 |
| July | 23 |
| August | 22 |
| September | 20 |
| October | 23 |
| November | 23 |
| December | 21 |
+-----------+--------+
I would like to have a new column, exactly like the courses one, but for the absences.
My Absence columns are : id, user_id, course_id, reason, justified
So, is this possible to use the courses group by with an absence count ?
If yes, how ?
Thanks in advance,
EDIT :
I have now this query :
SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month) a
INNER JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS absences
FROM Absence a
LEFT JOIN Course c
ON a.course_id = c.id
GROUP BY month) b
ON a.month = b.month;
And the result is :
+----------+---------+----------+
| month | courses | absences |
+----------+---------+----------+
| November | 23 | 2 |
| October | 23 | 1 |
+----------+---------+----------+
The numbers are good, but when there are no absences, the courses are not shown. Is there a way to have a 0 on the absences ?
EDIT 2 :
This is the working query :
SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month) a
LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS absences
FROM Absence a
LEFT JOIN Course c
ON a.course_id = c.id
GROUP BY month) b
ON a.month = b.month;