0

Not sure what this method might be called

I have a table

Pupil Payments Price
PupilA 100 100
PupilB 100 50
PupilB 100 0
PupilC 100 20

I am running a query as follows

SELECT Pupil, SUM(Payments), (SUM(Price) - SUM(Payments)) AS Balance , SUM(Price) 
FROM LessonSchedule
Group by Pupil Order By Balance Desc

Which gives

Pupil Payments Price Balance
PupilB 200 50 150
PupilC 20 100 80
PupilA 100 100 0

The problem I have with this query is that it gives all pupils, even if there is no outstanding balance.

I am looking to find a way to display only the pupils who have an outstanding balance

the desired result would look like

Pupil Payments Price Balance
PupilB 200 50 150
PupilC 20 100 80

Something like

SELECT Pupil, SUM(Payments), (SUM(Price) - SUM(Payments)) AS Balance , SUM(Price) 
FROM LessonSchedule
WHERE Balance !== 0
Group by Pupil 
Order By Balance Desc

I have tried WHERE Balance !== 0 but as the Balance column does not exist in the column, the query does not work.

I have also tried WHERE (SUM(Price) - SUM(Payments)) !==0 but this gives the same result.

Is there a recommended way to achieve the desired result?

I have also tried != in place of !==

1
  • (SQL questions belong on the sister site stackoverflow.com )
    – Rick James
    Commented Oct 13, 2022 at 22:16

1 Answer 1

2
SELECT Pupil,
       SUM(Payments),
       (SUM(Price) - SUM(Payments)) AS Balance , 
       SUM(Price) 
   FROM LessonSchedule
   Group by Pupil 
   HAVING Balance != 0
   Order By Balance Desc

WHERE works after gathering the data, but before doing GROUP BY.
HAVING works after GROUP BY.

Since the SUMs (and other aggregates) are done by "group by", you must wait until later for checking Balance.

Note: Balance is shorthand for (SUM(Price) - SUM(Payments)) in your example, so Balance includes an aggregate.

2
  • That seems to do the trick... I will monitor it as I add more data and make sure it continues to work correctly. You mentioned that, this may not be what I need... Is there much of a difference between Where and Having, it seems to do the same thing, bbut that is based on the limited entries I have
    – PaulMcF87
    Commented Oct 13, 2022 at 21:49
  • @PaulMcF87 - I explained further.
    – Rick James
    Commented Oct 13, 2022 at 22:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.