我有这张桌子
表名:com_inv
item_name amount date_added
item 1 1 06/06/2015
item 2 2 07/06/2015
item 3 3 08/06/2015
item 1 10 09/06/2015
item 2 20 10/06/2015
item 3 30 11/06/2015
表名:sls_ordrs
item_name amount order_status date_received
item 1 1 received 06/06/2015
item 2 1 delivered
item 3 2 received 08/06/2015
item 1 5 received 09/06/2015
item 2 5 delivered
item 3 2 received 11/06/2015
我想要达到的目标是,每个项目减去sls_ordrs中已经收到的金额总和"来自com_inv中金额的总和。结果表应如下所示:
Item Name Stocked Dispensed Remaining
item 1 11 6 5
item 2 22 0 22
item 3 33 4 29
如果我使用SQL Server,我只会使用CTE但是使用MySql我需要你的帮助。这是我到目前为止提出的代码......
SELECT
a.item_name,
b.stocked AS 'Stocked',
sum(a.amount) AS 'Dispensed',
IFNULL(b.stocked, 0) - IFNULL(a.amount, 0) AS 'Remaining'
FROM
sls_ordrs a
LEFT JOIN (
SELECT
item_name AS 'item_name',
SUM(amount) AS 'stocked'
FROM
com_inv
GROUP BY
item_name
) b ON a.item_name = b.item_name
WHERE
a.order_status = 'received'
GROUP BY
item_name
这里的库存列给了我一个空值。
答案 0 :(得分:1)
使用此查询。希望它应该工作正常。
SELECT
I.item_name,
I.Stocked,
S.Dispensed,
COALESCE (I.Stocked, 0) - COALESCE (S.Dispensed, 0) AS Remaining
FROM
(
SELECT
item_name AS 'item_name',
SUM(amount) AS 'Stocked'
FROM
com_inv
GROUP BY
item_name
) I
LEFT JOIN (
SELECT
item_name,
order_status,
SUM(amount) AS Dispensed
FROM
sls_ordrs
WHERE
order_status = 'received'
GROUP BY
item_name
) S ON I.item_name = S.item_name;