Question

this is my first posting here and i hope i made nothing wrong.

I do get wrong results with sum because i do not understand how to write my query in the correct way.

I have three tables, the first is the master and 2 identical child tables. The child tables are used for expense and income.

Table forecast

id  forecast_id
1   721     
2   721
3   721 

Table expense

forecast_id     amount      tax_free
721             100         0
721             200         1
721             300         0

Table income

forecast_id     amount      tax_free
721             50          1
721             100         0

SELECT
    t_forecast.forecastID,
    Sum(t_fc_einkauf.betrag) AS expense,
    Sum(t_fc_zahlung.betrag) AS income
FROM
    t_forecast
JOIN t_fc_einkauf ON t_fc_einkauf.forcastID = t_forecast.forecastID
JOIN t_fc_zahlung ON t_fc_zahlung.forcastID = t_forecast.forecastID
WHERE
    t_forecast.forecastID = 855
ORDER BY

My result is wrong

forcastID   expense     income
855         1200        450

It should be

forcastID   expense     income
855          600        150
Was it helpful?

Solution

You are using joins which creates cross product rows and therefore you are getting sum higher than expected try this with correlated subquery

SELECT
   DISTINCT f.forecast_id,
(SELECT SUM(e.amount) FROM expense e WHERE e.forecast_id = f.forecast_id )
AS expense,
 (SELECT SUM(i.amount) FROM income i WHERE i.forecast_id = f.forecast_id )
AS income
FROM
   forecast f
WHERE
    f.forecast_id = 721

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top