我有两个表,表P和表Q,每行10行和2行。
当我从表P中减去(找到数量)表Q时,通过使用下面的代码,减法影响到所有(10行)行。减法将基于批号。
请参阅我使用的代码:
select p.batch,p.QTY-COALESCE(q.QTY,0) INSTOCK from
(
select a.[ITEM CATEGORY NAME] cat,b.[ITM SUB CATEGORY NAME] subcat,c.[ITM BRAND DES] brand,d.[BTH NAME] batch,SUM(e.[INV QUANTITY]) QTY
from dbo.ITEM_CATEGORY a,dbo.ITM_SUB_CATEGORY b,dbo.ITM_BRAND_DES c,dbo.STK_BATC`enter code here`H d,dbo.INVENTORY_MASTER e
where
a.[ITEM CATEGORY ID]=e.[INV CATEGORY] and
b.[ITM SUB CATEGORY ID]=e.[INV ITEM NAME ID] and
c.[ITM BRAND ID]=e.[INV ITEM BRAND ID] and
d.[BTH ID]=e.[INV BATCH ID] and
e.[INV PROCESS]='IN'
group by a.[ITEM CATEGORY NAME],b.[ITM SUB CATEGORY NAME],c.[ITM BRAND DES],d.[BTH NAME],e.[INV BATCH ID]) AS p
CROSS APPLY
(select a.[ITEM CATEGORY NAME] cat,b.[ITM SUB CATEGORY NAME] subcat,c.[ITM BRAND DES] brand,d.[BTH NAME] batch,COALESCE(SUM(e.[INV QUANTITY]),0) QTY
from dbo.ITEM_CATEGORY a,dbo.ITM_SUB_CATEGORY b,dbo.ITM_BRAND_DES c,dbo.STK_BATCH d,dbo.INVENTORY_MASTER e
where
a.[ITEM CATEGORY ID]=e.[INV CATEGORY] and
b.[ITM SUB CATEGORY ID]=e.[INV ITEM NAME ID] and
c.[ITM BRAND ID]=e.[INV ITEM BRAND ID] and
d.[BTH ID]=e.[INV BATCH ID] and
e.[INV PROCESS]='OUT'
group by a.[ITEM CATEGORY NAME],b.[ITM SUB CATEGORY NAME],c.[ITM BRAND DES],d.[BTH NAME],e.[INV BATCH ID]) AS q
我知道理解起来很复杂,但您会了解我的编码方式。有没有最好的方法从另一个表中减去一个表?
答案 0 :(得分:0)
以下任何原因都无法使用?
select
p.batch, p.QTY INSTOCK
from
(select
a.[ITEM CATEGORY NAME] cat,
b.[ITM SUB CATEGORY NAME] subcat,
c.[ITM BRAND DES] brand,
d.[BTH NAME] batch,
SUM(
CASE
WHEN e.[INV PROCESS] = 'OUT'
THEN
-e.[INV QUANTITY]
ELSE
e.[INV QUANTITY]
END) QTY
from dbo.INVENTORY_MASTER e
join dbo.ITEM_CATEGORY a
ON a.[ITEM CATEGORY ID]=e.[INV CATEGORY]
join dbo.ITM_SUB_CATEGORY b
ON b.[ITM SUB CATEGORY ID]=e.[INV ITEM NAME ID]
join dbo.ITM_BRAND_DES c
ON c.[ITM BRAND ID]=e.[INV ITEM BRAND ID]
join dbo.STK_BATCH d
ON d.[BTH ID]=e.[INV BATCH ID]
where
e.[INV PROCESS] IN ('IN','OUT')
and
e.[INV ITEM BRAND ID] = @EnterCodeHere
group by
a.[ITEM CATEGORY NAME],
b.[ITM SUB CATEGORY NAME],
c.[ITM BRAND DES],
d.[BTH NAME],
e.[INV BATCH ID]) AS p