你好,我想問一下關於總和查詢,我在執行查詢時遇到困惑。ASK MySQL查詢SUM不同表
我想計算總電流。
SUM對於進入材料
select (select sum(jumlah) from warehouse where tgl_invoice >= '2013-03-17' AND
tgl_invoice <='2013-03;18' and kode=a.kode) total,a.kode,a.nama from warehouse a
group by a.kode;
結果:
+-------+---------+------------+ | total | kode | nama | +-------+---------+------------+ | 4 | ACLG001 | AC LG 1 pk | | 180 | P001 | Spindle | | 40 | S012 | Cable | +-------+---------+------------+
SUM對於使用的材料(貨物)
select (select sum(jumlah) from use_material where tanggal >= '2013-03-17' AND
tanggal <='2013-03;18' and kode_barang=a.kode) total,a.kode,a.nama from warehouse a
group by a.kode;
結果:
+-------+---------+------------+ | total | kode | nama | +-------+---------+------------+ | NULL | ACLG001 | AC LG 1 pk | | 20 | P001 | Spindle | | 10 | S012 | Cable | +-------+---------+------------+
現在我要總結來料(貨物)減去使用的材料(商品)
select
(select sum(jumlah) from warehouse
where tgl_invoice >= '2013-03-17' AND tgl_invoice <='2013-03;18' and kode=a.kode) -
(select sum(jumlah) from use_material
where tanggal >= '2013-03-17' AND tanggal <='2013-03;18' and kode_barang=a.kode)
total,a.kode,a.nama from warehouse a group by a.kode;
結果:
+-------+---------+------------+ | total | kode | nama | +-------+---------+------------+ | NULL | ACLG001 | AC LG 1 pk | | 160 | P001 | Spindle | | 30 | S012 | Cable | +-------+---------+------------+
這裏是計算錯誤。應交流LG 1 PK必須估價4.但在結果NULL
請回答。
如何使用COALESCE語句 – yusronnube
TRY:select COALESCE(select sum(jumlah)from use_material where tanggal> ='2013-03-17'AND tanggal <='2013-03; 18'and kode_barang = a.kode ),0)a.kode,a.nama來自倉庫a 組by akode; –
本質上,COALESCE採用參數,它只是返回提供的第一個非空值。它被用於_precisely_這種事情。你不能從某物中減去null。你得到空...所以你與0結盟讓你可以使用。希望它有所幫助。 –