使用/ CTE更新SQL表并从另一个表更新多个结果

时间:2013-10-09 09:52:33

标签: sql sql-server common-table-expression

我正在使用以下查询;但它不起作用。挑战是e.Value可以为每个文档返回多个结果(因此每个设备),我想用最新的e.Value(因此是ORDER BY d.CreatedDate)更新Equipment.LastCheck。

无论我尝试什么,都不会更新Equipment.LastCheck。谁能告诉我我做错了什么?

WITH cte
     AS (SELECT eq.LastCheck,
                e.Value                                         AS Result,
                ROW_NUMBER() OVER (ORDER BY d.CreatedDate DESC) AS Rn
         FROM   Equipment eq
                INNER JOIN Documents d
                  ON d.EquipmentId = eq.EquipmentId
                INNER JOIN Elements e
                  ON e.ElementId = d.ElementId
         WHERE  e.Name = 'CheckDate'
                AND e.Value IS NOT NULL)
UPDATE cte
SET    LastCheck = Result; 

2 个答案:

答案 0 :(得分:0)

尝试这个:

WITH cte
     AS (SELECT eq.LastCheck,
                e.Value                                         AS Result,
                ROW_NUMBER() OVER (ORDER BY d.CreatedDate DESC) AS Rn
         FROM   Equipment eq
                INNER JOIN Documents d
                  ON d.EquipmentId = eq.EquipmentId
                INNER JOIN Elements e
                  ON e.ElementId = d.ElementId
         WHERE  e.Name = 'CheckDate'
                AND e.Value IS NOT NULL)
UPDATE cte
SET    LastCheck = Result
WHERE Rn = 1

答案 1 :(得分:0)

这是一种不使用CTE的方法:

UPDATE eq
SET eq.LastCheck = e.Value
FROM Equipment eq
  INNER JOIN Documents d ON d.EquipmentID = eq.EquipmentID
  INNER JOIN Elements e ON e.ElementID = d.ElementID
WHERE d.EquipmentID = eq.EquipmentID 
  AND e.Name = 'CheckDate'
  AND e.Value IS NOT NULL
  AND NOT EXISTS (
    SELECT *
    FROM Documents d2
      INNER JOIN Elements e2 ON e2.ElementID = d2.ElementID 
    WHERE d2.CreatedDate > d.CreatedDate AND d2.EquipmentID = eq.EquipmentID
  )

NOT EXISTS语句确保返回具有最新CreatedDate的文档记录。


<强>更新 使用CTE更有效。正如Martin Smith的评论中所建议的那样,完成了你想要的完成查询,包括PARTITION BY eq.EquipmentID和WHERE Rn = 1。

WITH cte AS (
    SELECT  eq.LastCheck,
            e.Value AS Result,
            ROW_NUMBER() OVER (
                PARTITION BY eq.EquipmentID 
                ORDER BY d.CreatedDate DESC
            ) AS Rn
    FROM Equipment eq
        INNER JOIN Documents d ON d.EquipmentId = eq.EquipmentId
        INNER JOIN Elements e ON e.ElementId = d.ElementId
    WHERE e.Name = 'CheckDate'
        AND e.Value IS NOT NULL
)
UPDATE cte
SET LastCheck = Result
WHERE Rn = 1