MYSQL对表进行分组并应用汇总减法

时间:2017-12-03 16:32:30

标签: php mysql sorting addition subtraction

tablo1
----------------------------------- ---
firma与 ---------------------的 alacak
Firma1- ------------------ 500
Firma1 ------------------- 300
Firma1- ------------------ 700
Firma2 ------------------- 400
Firma2- ------------------ 200

tablo2
----------------------------------- ---
firma与 ---------------------的 tahsilat
Firma1- ------------------ 300
Firma1 ------------------- 200
Firma2- ------------------ 100

我有2张桌子。我想分组和聚合" firma"在表1和表2中。我想得到结果。

(" tablo1" Firma1 - > 1500) - (" tablo2" Firma1 - > 500)= 1200
(" tablo1" Firma2 - > 600) - (" tablo2" Firma2 - > 100)= 500


我要打印的结果:
firma --------- alacak
Firma1-- ----- 1200
Firma2 ------- 500

我尝试了这样的代码:

SELECT tablo1.firma,
       (COALESCE(tablo1.alacak) - COALESCE(tablo2.tahsilat)) AS sonuc
FROM (SELECT firma, SUM(alacak) AS alacak
      FROM tablo1
      GROUP BY firma
     ) AS tablo1 LEFT JOIN
     (SELECT firma, SUM(tahsilat) AS tahsilat
      FROM tablo2
      GROUP BY firma
     ) AS tablo2
     ON tablo1.firma = tablo2.tahsilat
ORDER BY tablo1.firma ASC

1 个答案:

答案 0 :(得分:0)

您的代码可以使用正确的ON tablo1.firma = tablo2.firma 条件:

union all

但是,在MySQL中,我更喜欢使用group byselect firma, sum(amount) from ((select firma, alacak as amount from tablo1 ) union all (select firma, - tahsilat from tablo2 ) ) tt group by firma;

setDaemon(True)

即使记录只在一个表中,也不管它们所在的表是什么,这都有效。