SQL Update查询来自另一个表的sum和first行

时间:2017-08-04 03:54:39

标签: sql-server

我正在创建SQL查询,它将更新表A'的数量。来自表B'。但是,表B中的几个字段不是总和,它们的最新值(基于日期顺序的第一行或最后一行值)也要在表A'中更新。下面是查询信息。

UPDATE r
SET r.Completed = t.MoveQty, r.Scrapped = t.ScrapQty, r.ReWork = t.ReworkQty
FROM JobRoutings r
INNER JOIN
(
  SELECT JobID, ScanFromProcessID, SUM(ScanMoveQty) MoveQty, Sum(ScanScrapQty) ScrapQty, Sum(ScanRecutQty) ReworkQty
  FROM JobTrans
  GROUP BY  JobID, ScanFromProcessID
) t ON r.JobID = t.JobID AND r.ProcessID  = t.ScanFromProcessID;

上述查询中需要包含的字段为:

[JobTrans]的最新值.ScannedDate和[JobTrans]。PC [ORDER BY ScannedDate]需要更新[JobRoutings]。LastScanDate和[JobRoutings] .PC

1 个答案:

答案 0 :(得分:1)

这是一种连接第二个子查询并使用ROW_NUMBER()获取最新PC / ScannedDate值的方法:

UPDATE r
SET r.Completed = t.MoveQty, r.Scrapped = t.ScrapQty, r.ReWork = t.ReworkQty, r.LastScanDate = t.ScannedDate, r.PC = t.PC
FROM JobRoutings r
INNER JOIN
(
  SELECT JobTrans.JobID, JobTrans.ScanFromProcessID, t2.ScannedDate, t2.PC, SUM(ScanMoveQty) MoveQty, Sum(ScanScrapQty) ScrapQty, Sum(ScanRecutQty) ReworkQty
  FROM JobTrans 
  INNER JOIN
  (
      SELECT JobID, ScanFromProcessID, ScannedDate, PC, ROW_NUMBER() OVER (PARTITION BY JobID, ScanFromProcessID ORDER BY ScannedDate DESC) AS rn
      FROM JobTrans
  )t2 ON JobTrans.JobID = t2.JobID AND JobTrans.ScanFromProcessID = t2.ScanFromProcessID AND t2.rn = 1
  GROUP BY  JobTrans.JobID, JobTrans.ScanFromProcessID, t2.ScannedDate, t2.PC
) t ON r.JobID = t.JobID AND r.ProcessID  = t.ScanFromProcessID