我有銷售標題和銷售行表。例如,SalesID = 1 在銷售線表中有 2 條銷售線。
SalesHeader:
銷售 ID = 1,活動 = 1
如果所有行的銷售狀態都已開票,我想將 Active 標志設定為 0
SalesLines
SalesID = 1,lineNum = 1,SalesStatus = Invoiced
SalesID = 1,lineNum = 2,SalesStatus = 未結訂單
在這種情況下,我不想將標題表中的活動標志更改為 0,因為同一銷售訂單中的 1 行是未結訂單。
如果所有行都已開票,我想更改活動標志 = 0。
uj5u.com熱心網友回復:
1- 找到您需要更新的 ID。您可以檢查 ID 的所有可用 salesLines 的數量,并將其與“Invoiced”計數的總數進行比較,該計數應該與其更新的標志匹配。您可以將這些 id 保存到單獨的臨時表中,因為您也可以使用表型別的變數或“with cte”結構。
SELECT SalesId
into #SalesHavingAllInvoicedLines
from
(
SELECT SalesId,
COUNT(*) totCount,
SUM(CASE WHEN SalesStatus ='invoiced' THEN 1 ELSE 0 END) InCount
FROM SalesLines
GROUP BY SalesId
) x
WHERE x.totCount=x.InCount
2- 使用“內部聯接”對您在步驟 1 中創建的臨時表進行更新。
update s
set Active=0
from SalesHeader s
inner join #SalesHavingAllInvoicedLines s2 on s.SalesId=s2.SalesId
uj5u.com熱心網友回復:
通常,在不需要精確值時或在不需要精確值時exists執行得更好。你所描述的一個相當清楚的表達是:countsum
update SalesHeader
set Active = 0
where not exists ( -- Note: NOT exists.
-- Find all of the corresponding sales lines with a sales status other than "Invoiced" .
select 42
from SalesLines as SL
where SL.SalesId = SalesHeader.SalesId and SL.SalesStatus <> 'Invoiced' );
SalesLines表上的索引SalesId和包括SalesStatus將是有用的。
請注意,如果其中沒有SalesLines匹配的行,SalesId則將Active設定為0.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460688.html
