根据子记录更新父表

时间:2016-03-28 04:30:48

标签: sql-server sql-server-2008

大家好我想更新父表的状态取决于子记录。

条件是。

  

具有字段Isclosed的子记录。

  1. 如果所有子记录Isclosed=1则父记录状态= 1
  2. 如果某些子记录Isclosed=1,则父记录状态= 2
  3. 其他父记录状态= 3
  4. 我试过这个:

    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))
    

    但它只满足一个条件。

3 个答案:

答案 0 :(得分:3)

您可以使用CTE获取COUNTChild条记录IsClosed = 1以及COUNTChild条记录每Parent。然后使用CTEUPDATE 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

SQL Fiddle

答案 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为。