使用group by更新列值

时间:2017-11-08 14:13:42

标签: sql sql-server

我有一个如下表格,需要更新因子ido的Value列。我想通过执行以下操作来更新ido值

   ido Value = top Value - sos Value

表示每种日期和方法类型。

当前表:

   DateP        Factor     Value     Method
  ------------------------------------------
   2017-01-01   top        23        w
   2017-01-01   sos        15        w
   2017-01-01   ido        20        w
   2017-01-01   top        29        M
   2017-01-01   sos        10        M
   2017-01-01   ido        2         M
   2017-02-02   top        101       w
   2017-02-02   sos        60        w
   2017-02-02   ido        20        w

所以希望下面的表格能说明我想要实现的目标

更新后的所需表:

   DateP        Factor     Value     Method
   -----------------------------------------
   2017-01-01   top        23        w
   2017-01-01   sos        15        w
   2017-01-01   ido        8         w
   2017-01-01   top        29        M
   2017-01-01   sos        10        M
   2017-01-01   ido        19        M
   2017-02-02   top        101       w
   2017-02-02   sos        60        w
   2017-02-02   ido        41        w

2 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN

UPDATE A
SET a.[Value] = b.TopValue - b.SosValue
FROM dbo.YourTable a
INNER JOIN (SELECT  DateP, 
                    Method, 
                    MIN(CASE WHEN Factor = 'top' THEN [Value] END) TopValue,
                    MIN(CASE WHEN Factor = 'sos' THEN [Value] END) SosValue
            FROM dbo.YourTable
            GROUP BY DateP, 
                     Method) b
    ON a.DateP = b.DateP
    AND A.Method = b.Method
WHERE a.Factor = 'ido'
;

答案 1 :(得分:1)

我会使用窗口函数和可更新的CTE来执行此操作:

with toupdate as (
      select t.*,
             sum(case when factor = 'top' then value
                      when factor = 'sos' then - value
                 end) over (partition by date, method) as new_value
      from t
     )
update toupdate
    set value = new_value
    where method = 'ido';