Home > database >  How to Sum tables with Left Join and pre aggregate
How to Sum tables with Left Join and pre aggregate

Time:12-02

I have 3 tables to calculate payments, received and paid:

  1. Company
idcompany company
1 APPLE
2 GOOGLE
3 MICROSOFT
4 STEAM
5 AMAZON
6 LG
  1. Pay:
id company dueday valuep
1 APPLE 03/10/2022 200,00
2 APPLE 04/10/2022 600,00
3 GOOGLE 04/10/2022 600,00
4 MICROSOFT 04/10/2022 500,00
5 MICROSOFT 04/10/2022 60,00
6 APPLE 04/10/2022 100,00

3.Receive:

idconta company issuedate valuer
104 MICROSOFT 03/10/2022 70000,00
106 STEAM 03/10/2022 15000,00
107 STEAM 03/10/2022 42000,00
108 AMAZON 03/10/2022 46000,00
109 LG 03/10/2022 3200,00

I need to make a report with amount paid and received during a certain period, but somehow its duplicating sum and I getting this result:

company value_pay value_receive
AMAZON NULL 46000.00
APPLE 900.00 NULL
GOOGLE 600.00 NULL
LG NULL 3200.00
MICROSOFT 560.00 140000.00
SHOPPING NULL 20000.00
STEAM NULL 57000.00

I tried this query:

SELECT o.company, 
       SUM(n.valuep) AS value_pay, 
       SUM(r.valuer) AS value_receive 
FROM app_company AS o 
LEFT JOIN app_pay AS n ON o.idcompany=n.company AND (date(n.duedate) BETWEEN '2022-10-01' AND '2022-10-30') 
LEFT JOIN app_receive AS r ON o.idcompany=r.company AND (date(r.issuedate) BETWEEN '2022-10-01' AND '2022-10-30') 
GROUP BY o.company

I tried LEFT JOIN to get all results even if it is empty in one of columns, I tried to pre-aggregate, but I could not get my query to work. I am missing something.

CodePudding user response:

You need to do the aggregation on the subqueries and then join .

SELECT o.company, 
       value_pay, 
       value_receive 
FROM app_company AS o 
LEFT JOIN  (select sum(valuep) as value_pay,
                   company
            from app_pay
            where date(dueday) BETWEEN '2022-10-01' AND '2022-10-30'
            group by company
             ) AS n ON o.company=n.company 
LEFT JOIN  (select sum(valuer)  AS value_receive ,
                   company
            from app_receive
            where date(issuedate) BETWEEN '2022-10-01' AND '2022-10-30' 
            group by company
            )  AS r ON o.company=r.company 
order by o.company asc   ;

https://dbfiddle.uk/0mVKI_tF

  • Related