Search code examples
mysqlsumsubtraction

3 table addition and subtraction


I have three tables:

Description of tablo1 and tablo2 and tablo3

I want to group all the results according to Table 3 collection operation and year.

Here is an example of what I want:

tablo1
2017 -> 2100(alacak)

tablo2
2017 -> 600(borc)

  • 2100(alacak) - 600(borc) = 1600(result)

tablo3
2017 -> 600(gider)

  • 1600(result) - 600(gider) = 1000(final)

I tried a code like this:

SELECT tablo1.year, (SUM(tablo1.alacak)-SUM(tablo2.borc)-SUM(tablo3.gider)) AS result
FROM
    tablo1 JOIN tablo2 ON tablo1.alacak = tablo2.borc        
    LEFT JOIN giderler ON tablo1.alacak = tablo3.gider
    GROUP BY tablo1.year DESC;

But it doesn't work. Any help will be appreciated.


Solution

  • Is this what you want???

    select year,
     (select sum(alacak) quantity 
          from table1 
        where table1.year = t3.year) 
        -
     (select sum(borc) quantity
        from table2 
       where table2.year = t3.year)
       - 
     (select sum(gider) quantity 
        from table3
       where table3.year = t3.year) as result
       from table3 t3
       group by year;