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.