我在列中有示例值,如下所示:
values
-------
89
65
56
78
74
73
45
23
5
654
643
543
345
255
233
109
43
23
2
值上升然后下降到0并再次上升。 我需要计算新列中行之间的差异以及所有值的这些差异之和(累积和)。值56和5是零的新差异 总和是819。 底部的例子> (23-2)+(43-23)+(109-43)+ .. +(654-643)+(5)+(23-5)+ ..
答案 0 :(得分:1)
好的,这是我的尝试。但是,您需要添加一个标识字段(我称之为“AddSequence”),该字段以1开头表示第一个值(“2”),并为每个其他值加1。
SELECT SUM(C.Diff) FROM
(
SELECT CASE WHEN (A.[Value] - (SELECT [Value] FROM [TestValue] AS B WHERE B.[AddSequence]= A.[AddSequence]-1)) > 0
THEN (A.[Value] - (SELECT [Value] FROM [TestValue] AS D WHERE D.[AddSequence]= A.[AddSequence]-1))
ELSE 0
END AS Diff
FROM [TestValue] AS A
) AS C
我忽略了第一个解决方案,即每当差异为负时我们必须重新开始。
答案 1 :(得分:0)
我认为你正在寻找类似的东西:
SELECT SUM(a - b)) as sum_of_differences
FROM ...
答案 2 :(得分:0)
已编辑 - 基于您的问题编辑(T-SQL)
我不知道如何在不添加ID的情况下执行此操作。
如果您添加了ID,则会显示您在编辑之前发布的确切输出。可能有更好的方法,但这很快又很脏 - 一次性拍摄。使用SELF JOIN
。差异是最初新列的名称。
UPDATE A
SET differences = CASE WHEN A.[values] > B.[Values] THEN A.[values] - B.[Values]
ELSE A.[values] END
FROM SO_TTABLE A
JOIN SO_TTABLE B ON A.ID = (B.ID - 1)
输出
Select [Values], differences FROM SO_TTABLE
[values] differences
------------------------
89 24
65 9
56 56
78 4
74 1
73 28
45 22
23 18
5 5
654 11
643 100
543 198
345 90
255 22
233 124
109 66
43 20
23 21
2 0
答案 3 :(得分:0)
我认为你想要这个差异,我已经在sqlite中测试过了
SELECT CASE WHEN (v.value - val) < 0 THEN 0 ELSE (v.value - val) END AS differences
FROM v,
(SELECT rowid, value AS val FROM v WHERE rowid > 1) as next_val
WHERE v.rowid = next_val.rowid - 1
总和
SELECT SUM(differences) FROM
(
SELECT CASE WHEN (v.value - val) < 0 THEN 0 ELSE (v.value - val) END AS differences
FROM v,
(SELECT rowid, value AS val FROM v WHERE rowid > 1) AS next_val
WHERE v.rowid = next_val.rowid - 1
)