[Solved] Double SUM query MySQL

[ad_1]

Given the tables:

Tabel_1

idUnitBudget
1121000
1122000

Tabel_2

idUnitReal2
112500
112100

You can produce the following result:

idUnitTotalBudgetTotalReal2
1123000600

With the following query:

SELECT t1.idUnit, SUM(Budget) AS TotalBudget, t2.TotalReal2
FROM Tabel_1 AS t1
  JOIN (SELECT idUnit, SUM(Real2) AS TotalReal2
        FROM Tabel_2 GROUP BY idUnit
  ) AS t2 ON t1.idUnit = t2.idUnit
GROUP BY t1.idUnit;

What we’ve done is group the results of joining the two tables by the idUnit which means that each value of idUnit will only show up once in the result. Then, we’ve used the SUM() aggregate function twice (once for each column we want to sum) to add the values for each idUnit together.

Try it out!

10

[ad_2]

solved Double SUM query MySQL