1
更新語句我有以下查詢:使用子查詢
DECLARE @fromdate date = '2016-09-01'
DECLARE @todate date = '2016-10-03'
SELECT
inventoryKey,
SUM(DATEDIFF(DAY, transdate, @todate) * qty) AS daysavailable
FROM
(SELECT
InventoryKey,
CONVERT(date, invch.transactiondate) AS transdate,
SUM(invch.additionqty + invch.SubtractionQty) AS qty
FROM
dw.dbo.inventorychange invch
WHERE
(TransactionDate IS NOT NULL OR TransactionType <> '')
AND TransactionType NOT IN ('TRANSFER IN', 'TRANSFER OUT', 'BALANCE', 'LEASED')
AND InventoryKey = 'A000HV9T'
AND TransactionDate BETWEEN @fromdate AND @todate
GROUP BY
invch.TransactionDate, InventoryKey) AS a
GROUP BY
InventoryKey
這工作對自己完全沒問題。不過,我正在創建一個存儲過程,它將執行一些計算,其中之一就是上面的計算。存儲過程將返回一個表,其中此列將用實際值進行更新。但是,我不完全知道如何在子查詢更新語句中準確地翻譯它。
這是我下面有:
declare @inventorychanges table
(
inventorykey nvarchar(10),
warehouse nvarchar(10),
transdate date,
trantype nvarchar(25),
additionqty numeric,
subtractionqty numeric
)
insert into @inventorychanges (inventorykey, warehouse, transdate, trantype, additionqty, subtractionqty)
select invch.inventorykey, invch.warehouse, invch.TransactionDate, invch.TransactionType, invch.additionqty, invch.SubtractionQty
from dw.dbo.inventorychange invch
join @icodes ic on ic.inventorykey = invch.inventorykey
WHERE invch.TransactionDate BETWEEN @fromdate AND @todate
and invch.warehouse = ISNULL(@location, '')
AND (TransactionDate IS NOT NULL OR TransactionType <> '')
AND TransactionType NOT IN ('TRANSFER IN' ,'TRANSFER OUT', 'BALANCE', 'LEASED')
/* Update Days Available*/
UPDATE ic
SET ic.daysavaialblepsgear = (
SELECT SUM(invch.additionqty + invch.subtractionqty)
)
FROM @icodes ic, @inventorychanges invch
where invch.inventorykey = ic.inventorykey
然而,這似乎並沒有被工作所應當的。 任何人都可以指出我在正確的方向,我如何才能做到這一點。
我不認爲這是正確的。這是內部嵌套的子查詢。我實際上需要基於最上面的原始查詢的值是SUM(DATEDIFF(DAY,transdate,@todate)* qty)AS daysavailable – a415
@ a415 - 很好,更新我的回答 –
.....我可以使用內部存儲過程。 – a415