大家好我想更新父表的状态取决于子记录。
条件是。
具有字段
Isclosed
的子记录。
Isclosed=1
则父记录状态= 1 Isclosed=1
,则父记录状态= 2 我试过这个:
update Parent set Status=1
where id in(
select ParentID from Child where
Isclosed=1
group by ParentID having count(id)=(select count(id)from Child where Parent.id=ParentID))
但它只满足一个条件。
答案 0 :(得分:3)
您可以使用CTE
获取COUNT
个Child
条记录IsClosed = 1
以及COUNT
条Child
条记录每Parent
。然后使用CTE
到UPDATE
Parent
记录状态的结果:
WITH Cte AS(
SELECT
p.Id,
ClosedCount = SUM(CASE WHEN c.IsClosed = 1 THEN 1 ELSE 0 END),
TotalCount = COUNT(*)
FROM Parent p
INNER JOIN Child c
ON c.ParentId = p.Id
GROUP BY p.Id
)
UPDATE p
SET p.Status =
CASE
WHEN c.ClosedCount = c.TotalCount THEN 1
WHEN c.ClosedCount = 0 THEN 3
ELSE 2
END
FROM Parent p
INNER JOIN Cte c
ON c.Id = p.Id
答案 1 :(得分:0)
试试这个简单的查询,可能会帮到你
UPDATE P
SET P.status = (CASE WHEN MaxIsclosed = MinIsclosed AND MaxIsclosed > 0 THEN 1
WHEN MaxIsclosed > 0 THEN 2 ELSE 3 END)
FROM Parent P
LEFT OUTER JOIN (SELECT PARENTID,MAX(Isclosed) AS MaxIsclosed,MIN(Isclosed) AS MinIsclosed
FROM CHILD GROUP BY PARENTID) C ON P.PARENTID = C.PARENTID
答案 2 :(得分:0)
只需完成以下查询。
UPDATE [Parent]
SET [Status] = CASE WHEN EXISTS ( SELECT [ParentID]
FROM [Child]
WHERE [ParentID] = [Parent].[id]
GROUP BY [ParentID]
HAVING SUM([Isclosed]) = COUNT([ParentID])
)
THEN 1
WHEN EXISTS ( SELECT [ParentID]
FROM [Child]
WHERE [ParentID] = [Parent].[id]
GROUP BY [ParentID]
HAVING SUM([Isclosed]) = 0
)
THEN 3
ELSE 2
END
如果需要,您可以将[已关闭] CAST为。