表有2个列:[nr]和[diff]
diff是空的(到目前为止 - 需要填充)
nr有数字:
1
2
45
677
43523452
差异列上的我需要添加对之间的差异
1 | 0
2 | 1
45 | 43
677 | 632
43523452 | 43522775
所以基本上是这样的:
update tbl set diff = @nr - @nrold where nr = @nr
但我不想下次使用fetch,因为它不酷,而且速度很慢(100.000)记录
如何通过一次更新来实现这一目标?
答案 0 :(得分:0)
CREATE TABLE #T(nr INT,diff INT)
INSERT INTO #T (nr) SELECT 1
UNION SELECT 2
UNION SELECT 45
UNION SELECT 677
UNION SELECT 43523452
;WITH cte AS
(
SELECT nr,diff, ROW_NUMBER() OVER (ORDER BY nr) RN
FROM #T
)
UPDATE c1
SET diff = ISNULL(c1.nr - c2.nr,0)
FROM cte c1
LEFT OUTER JOIN cte c2 ON c2.RN+1= c1.RN
SELECT nr,diff FROM #T
DROP TABLE #T
答案 1 :(得分:0)
看看这样的事情(完整的例子)
DECLARE @Table TABLE(
nr INT,
diff INT
)
INSERT INTO @Table (nr) SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 45 UNION ALL
SELECT 677 UNION ALL
SELECT 43523452
;WITH Vals AS (
SELECT nr,
diff,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) xID
FROM @Table
)
UPDATE c
SET diff = c.nr - ISNULL(p.nr, 0)
FROM Vals c LEFT JOIN
Vals p ON c.xID = p.xID + 1
SELECT *
FROM @Table
答案 2 :(得分:-1)
试试这个 -
update tablename
set diff = cast(nr as INT) - cast((select nr from tablename where diff is not null and nr = a.nr) as INT)
from tablename a
where diff is null
这假设您在表中只有一个较旧的旧行。否则子查询将返回多个值