Given the tables:
Tabel_1
idUnit | Budget |
---|---|
112 | 1000 |
112 | 2000 |
Tabel_2
idUnit | Real2 |
---|---|
112 | 500 |
112 | 100 |
You can produce the following result:
idUnit | TotalBudget | TotalReal2 |
---|---|---|
112 | 3000 | 600 |
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.
10
solved Double SUM query MySQL