0

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

无论我尝试什么, 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; 
4

2 回答 2

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
于 2013-10-09T11:44:52.773 回答
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 的 Documents 记录。


更新: 使用 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
于 2013-10-09T14:39:36.250 回答