在具有不同条件的单个表中对2列数据求和

时间:2018-02-17 03:14:39

标签: php mysql

我有2个表jornal_mainjournal_item,我的journal_main表已经

id | po_no | period | post_date | vendor 1 | PO123 | 12 | 2018-02-12 | XYZ 2 | PO234 | 12 | 2018-02-13 | ABC

journal_item是 id | ref_id | type | sku | qty | desc 1 | 1 | poo | A123 | 12 | Order 2 | 1 | poo | B234 | 20 | Order 3 | 2 | por | A123 | 2 | Receive 4 | 2 | por | A123 | 3 | Receive 5 | 2 | por | B234 | 6 | Receive

期望的输出是 po_no | date | vendor | item | ordered_qty | received_qty | balance po123 | 2018-02-12 | XYZ | A123 | 12 | 5 | 7 po123 | 2018-02-12 | ABC | B234 | 20 | 6 | 14

我没有得到如何在一个查询中组合2个查询。这里我有2个查询,它们为我ordered_qtyreceived_qty

for ordered_qty

select journal_main.id, journal_main.po_no, journal_main.post_date, journal_main.vendor, journal_item. sku, SUM(journal_item.qty) AS Oqty FROM journal_main INNER JOIN journal_item ON journal_main.id=journal_item.ref_id WHERE journal_item.type='poo' GROUP BY journal_item.sku, journal_main.id

for received_qty

select journal_main.id, journal_main.po_no, journal_main.post_date, journal_main.vendor, journal_item. sku, SUM(journal_item.qty) AS Rqty FROM journal_main INNER JOIN journal_item ON journal_main.id=journal_item.ref_id WHERE journal_item.type='por' GROUP BY journal_item.sku, journal_main.id

1 个答案:

答案 0 :(得分:0)

只需使用条件聚合:

select ji.ref_id,
       sum(case when ji.desc = 'Order' then qty else 0 end) as ordered,
       sum(case when ji.desc = 'Receive' then qty else 0 end) as received,
       sum(case when ji.desc = 'Order' then qty else - qty end) as total
from journal_item ji
where ji.desc in ('Order', 'Receive')
group by ji.ref_id;

这只提供聚合列。您应该能够加入所需的其他列。