Skip to content
Advertisement

sql find parent table where sum of child column not equal to parent column

hey guys i am trying to find the a bill from billMaster where the sum of billDetails.total is not equal to billMaster.remainingAmount

NB this is a one to many relationship where one bill can contain more billdetails

i tried the below query and got an sql error

/* SQL Error (1111): Invalid use of group function */


SELECT a.id AS billMAsterId FROM eBillMaster AS a JOIN eBillDetail AS b ON a.id = b.billId
WHERE SUM(b.total) !=  b.remainAmount GROUP BY a.id 


SELECT a.remainAmount, a.id AS BillId FROM eBillMaster a JOIN (SELECT MAX(id) AS id FROM eBillMaster) b JOIN eBillDetail c ON (a.id - c.billId) WHERE SUM(c.total) != a.remainAmount

both queries returned the same error i gess its on how i used the sum on where close. But the sad thing is that i cant sole the problem.. Any response will be appreciated.

now assume i want to get recent user bill that meets the above condition . Note the billMaster has a column called user_id. how will the new query look like.

Advertisement

Answer

Thank you every one for your feedback it led me to the correct path and the modified query is

    SELECT m.propertyId, d.sumTotal, m.remainAmount, m.id
FROM eBillMaster AS m JOIN ( SELECT MAX(id) AS id FROM eBillMaster GROUP BY propertyId) b USING (id)
JOIN (select billId, sum(total) sumTotal from eBillDetail group by billId) AS d ON m.id = d.billId
WHERE d.sumTotal != m.remainAmount;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement