我正在使用MySQL,我有两个表:
master_table
stock_bal
主表格具有重复的ORDERNO
和ITEM
值。我使用SQL'GROUP BY'子句得到总QTY
。
我需要从BAL_QTY
(master_table)的SUM中扣除/减去ITEM
。我使用查询获得了SUM QTY
值(实际上有很多行)。
答案 0 :(得分:33)
我认为这就是你要找的东西。 NEW_BAL
是从余额中减去QTY
的总和:
SELECT master_table.ORDERNO,
master_table.ITEM,
SUM(master_table.QTY),
stock_bal.BAL_QTY,
(stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL
FROM master_table INNER JOIN
stock_bal ON master_bal.ITEM = stock_bal.ITEM
GROUP BY master_table.ORDERNO,
master_table.ITEM
如果要使用新余额更新项目余额,请使用以下命令:
UPDATE stock_bal
SET BAL_QTY = BAL_QTY - (SELECT SUM(QTY)
FROM master_table
GROUP BY master_table.ORDERNO,
master_table.ITEM)
这假设您向后发布了减法;它从天平中减去订单中的数量,这在不了解您的表格的情况下最有意义。如果我错了,只需交换这两个就改变它:
(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL
答案 1 :(得分:2)
我不确定你想要什么,但我认为这与以下几行有关:
SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B
答案 2 :(得分:0)
啊做作业......
等等,您需要从已订购商品的总数中扣除库存商品的余额吗?我必须告诉你,听起来有些倒退。一般来说,我认为人们会这样做。扣除从余额中订购的物品总数。
如果你确实需要那样做...... 假设ITEM在stock_bal中是独一无二的......
SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY
答案 3 :(得分:0)
我尝试过这种技术。将数据的减法乘以(-1)然后求和()两者的数量,然后你将得到减去的金额。
-- Loan Outstanding
select 'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
from
(
select
sum(laod.dr) as Unit,
sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
from loan_account_opening as lao
inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
where lao.organization = 3
union
select
sum(lr.installment)*-1 as Unit,
sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
from loan_recovery as lr
inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
where lo.organization = 3
) as t3
答案 4 :(得分:0)
下面给出了一个减法示例:
Select value1 - (select value2 from AnyTable1) from AnyTable2
value1和value2可以是计数,求和,平均输出等。但是这些值应该兼容
答案 5 :(得分:0)
带有子查询的简单复制和粘贴示例, 请注意,两个查询都应返回1行:
select
(select sum(items_1) from items_table_1 where ...)
-
(select count(items_2) from items_table_1 where ...)
as difference