[英]T-SQL Query to check if related col is true and update another table col
我有這2個表SupplierOrder和SupplierOrderDetails,它們由SupplierOrder PK鏈接。 現在,我在SupplierOrder表中擁有一個名為isComplete的列,一旦該SupplierORderDetails表的isComplete中的所有值對於該SupplierOrder ID都為true時,我希望將其更新為true。 請參閱表格附件。 我已經嘗試過使用此查詢,但我認為這可能是一種更好的方法,或更有效。
SELECT 1
FROM supplierOrder so
inner JOIN supplierOrderdetails sod
ON so.id = sod.supplierOrderID
WHERE so.id = 1
AND sod.isComplete= 1
這應該可以工作,我可能沒有正確的表名,但是如果您更改它就應該可以工作
UPDATE suplierorder
SET iscomplete = 'true'
WHERE id IN (SELECT suplierorderid
FROM (SELECT suplierorderid,
--case statement to set to 0 if complete and 1 if not complete (i.e any other value null or false)
Sum(CASE
WHEN iscomplete = 'true' THEN 0
ELSE 1
END) AS complete
FROM suplierorderdetails
--make sure we only update the new ones and makes sure that your select records are limited to Just not complete records, so if your tables grow this will make your update statement doesn't take a lot of time
WHERE suplierorderid IN (SELECT id
FROM suplierorder
WHERE iscomplete IS NULL)
--I am grouping on suplierorderid so that we can add all the iscomplete status of each suplierorderid column
GROUP BY suplierorderid) A
--now that the inner query outputs suplierorderid and complete status which will be 0 if everything is complete we are writing below condition
WHERE complete = 0)
我們需要的是找到supplierOrderID
其中MIN(isComplete)=1
。 所以這意味着ALL isComplete=TRUE
UPDATE supplierOrder SET isComplete=1
WHERE id in
(
SELECT supplierOrderID
FROM supplierOrderdetails
GROUP BY supplierOrderID
HAVING MIN(CAST(isComplete as Int))=1
)
AND
(
(isComplete is NULL ) OR (isComplete = 0)
)
PS:由於isComplete
是BIT
類型的字段,因此不能使用MIN(isComplete)
但可以使用MIN(CAST(isComplete as Int))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.