I am trying to determine how to do sum fields between two tables.
In table 1, we\'ll call it gegevens for short, I would have, for example, gegevenID, vertrekdatum,
Joining in any form will double the values when there are two gegevenID
rows in fees
(or triple them if there are three, and so on).
The best workaround I can think of is to calculate the sums independently - one subquery for price and one subquery for fees - and then put the results together:
SELECT
p.year,
p.SumOfPrijs,
f.SumOfFees,
p.SumOfPrijs + f.SumOfFees AS Total
FROM (
SELECT
YEAR(vertrekdatum) AS year,
SUM(prijs) AS SumOfPrijs
FROM gegevens
GROUP BY YEAR(vertrekdatum)
) p
LEFT JOIN (
SELECT
YEAR(vertrekdatum) as year,
SUM(amount) AS SumOfFees
FROM gegevens
INNER JOIN fees ON gegevens.gegevenID = fees.gegevenID
GROUP BY YEAR(vertrekdatum)
) f ON p.year = f.year
There's a SQL Fiddle here.
You need to use a subquery to aggregate the fees table before the join:
SELECT sum(prijs) as SumOfPrijs, sum(amount) as SumOfFees, sum(prijs)+sum(amount) AS
Total, year(vertrekdatum) as year
FROM tbl_vluchtgegevens vg LEFT JOIN
(select f.gegevenId, sum(amount) as Amount
from tbl_fees f
group by f.gegevenId
) f
ON f.gegevenID = vg.gegevenID
WHERE vertrekdatum <=NOW()
GROUP by year(vertrekdatum);
The problem is that the multiple fees on on "gegeven" is causing the join to produce unexpected rows, that affect the sum.