你好我想询问总和查询,我在执行查询时遇到了困惑。
我想计算总电流。
SUM IN INCOMING材料
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 | +-------+---------+------------+
现在我想要SUM 来料(商品)减去使用材料(商品)
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 | +-------+---------+------------+
这是计算错误。如果AC LG 1 PK必须值4.但结果为NULL
请回答。
答案 0 :(得分:1)
SQL COALESCE - 杀死空值应该有帮助。
e.g。 COALESCE(NULL,0)将给出0 ...使用NULL执行操作通常不起作用。
通过这个,我的意思是你在一个带有0的COALESCE中包装产生空值的查询(你显示的第二个查询)来给出一个有效的减法语句。
干杯。
答案 1 :(得分:0)
从仓库a中选择IFNULL(t.total,0,t.total),a.kode,a.nama
left join(从use_material选择kode_barang kode_barang,sum(jumlah)作为总数)
其中tanggal&gt; ='2013-03-17'AND tanggal&lt; =''2013-03-18'
由kode_barang分组)t.kode_barang = a.kode
分组由a.kode;