Tuesday 4 September 2018

SQL Query does not return rows when count (*) = 0 with the WHERE clause

I'm trying to write a query that returns the name of the school, the year of the payment, the cost of the payment and the number of students there was the year of the payment. The problem I encounter is that for a certain year there is 0 student so the query doesn't return any row although there was a payment.

Here is what i tried :
SELECT School.NAME,
       Payment.year,
       Payment.amount,
       Count(Student.id_stud) AS 'nb stud'
FROM   School
       LEFT JOIN Student
              ON school.id_school = Student.id_school
       LEFT JOIN Payment
              ON School.id_school = Payment.id_School
WHERE  Year(Student.date_in) <= Payment.year
GROUP  BY School.NAME,
          Payment.amount,
          Payment.year

I want to display every row even if the COUNT(Student.id_stud) is 0. I think that the problem is with the WHERE clause .

Move the Year(Student.date_in) filter to ON condition
SELECT School.NAME,
       Payment.year,
       Payment.amount,
       Count(Student.id_stud) AS 'nb stud'
FROM   School
       LEFT JOIN Student
              ON school.id_school = Student.id_school
       LEFT JOIN Payment
              ON School.id_school = Payment.id_School
             AND Year(Student.date_in) <= Payment.year
GROUP  BY School.NAME,
          Payment.amount,
          Payment.year

Where you filter the Year(Student.date_in) in Where clause, for the non matching Student.date_in will have NULL values. Those NULL values will be filtered by the where condition. So Move the filter to ON clause it tells what are records to be joined instead of filtering the result. Same logic will be applied to Payment.year as well.

0 comments:

Post a Comment