更新列并在同一查询中引用它

时间:2016-07-13 09:30:05

标签: sql sql-server

我在SQL Server 2014中有一个表,需要根据以前的值递归更新列。例如,

---------------------------------------
ID |   price   | diff_with_prev_price |
---------------------------------------
1  |   29      | 0                    |
2  |   25      | 0                    |
3  |   20      | 0                    |
4  |   35      | 0                    |
5  |   40      | 0                    |
--------------------------------------|

我想递归更新第三列,如下所示

---------------------------------------
ID |   price   | diff_with_prev_price |
---------------------------------------
1  |   29      | 0                    |
2  |   25      | 25                   |
3  |   20      | 5                    |
4  |   35      | -30                  |
5  |   40      | 10                   |
--------------------------------------|

它是第三列的先前值与下一个“价格”值的总和。 有人可以使用CTE或LEAD / LAG提供一些提示,但不使用游标。我必须更新百万行。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

SELECT 1 AS ID , 29 AS price, 0 AS diff_with_prev_prive
INTO #tmp
UNION SELECT 2 AS ID , 25 AS price, 0 AS diff_with_prev_prive
UNION SELECT 3 AS ID , 20 AS price, 0 AS diff_with_prev_prive
UNION SELECT 4 AS ID , 35 AS price, 0 AS diff_with_prev_prive
UNION SELECT 5 AS ID , 40 AS price, 0 AS diff_with_prev_prive

WITH cte AS 
(
    SELECT 
        ID
      , price
      , diff_with_prev_prive
      ,  price - ISNULL(LAG(price) OVER (ORDER BY ID),0) AS new_value
    FROM #tmp
)
UPDATE t
SET diff_with_prev_prive = t.new_value
FROM cte t

SELECT * FROM #tmp