计算不同表格的总和值

时间:2018-03-30 07:15:39

标签: mysql sql

这是我的代码:

SELECT barang.id_brg, barang.nm_brg, jen_sat, nm_kat, SUM( IFNULL(  stok_brg.stok, 0 ) ) AS stok, IFNULL( laku, 0 ) AS laku
        FROM barang
        JOIN satuan ON barang.id_sat = satuan.id_sat
        JOIN kategori ON barang.id_kat = kategori.id_kat
        LEFT JOIN stok_brg ON barang.id_brg = stok_brg.id_brg
        LEFT JOIN (
        SELECT barang.id_brg, SUM( IFNULL( brg_laku.dibeli, 0 ) ) AS laku
        FROM barang, brg_laku
        WHERE barang.id_brg = brg_laku.id_brg
        GROUP BY barang.id_brg ASC
        ) AS brg_laku ON barang.id_brg = brg_laku.id_brg
        GROUP BY barang.id_brg ASC

预览我的代码:

this preview of my code

问题是我想制作专栏 - laku并将结果作为专栏结果你们得到它对不起我对我的英语不好所以我不知道怎么说希望你们能理解我谢谢< / p>

1 个答案:

答案 0 :(得分:0)

您希望列stoklaku之间存在差异。如果是这样,试试这个:

select a.id_brg, a.nm_brg, a.jen_sat, a.nm_kat,a.stok,a.laku, (a.stok-a.laku) as difference
from (SELECT barang.id_brg, barang.nm_brg, jen_sat, nm_kat, SUM( IFNULL(  stok_brg.stok, 0 ) ) AS stok, IFNULL( laku, 0 ) AS laku
    FROM barang
    JOIN satuan ON barang.id_sat = satuan.id_sat
    JOIN kategori ON barang.id_kat = kategori.id_kat
    LEFT JOIN stok_brg ON barang.id_brg = stok_brg.id_brg
    LEFT JOIN (
    SELECT barang.id_brg, SUM( IFNULL( brg_laku.dibeli, 0 ) ) AS laku
    FROM barang, brg_laku
    WHERE barang.id_brg = brg_laku.id_brg
    GROUP BY barang.id_brg ASC
    ) AS brg_laku ON barang.id_brg = brg_laku.id_brg
    GROUP BY barang.id_brg ASC) as a;