SQL 服务器 - 反向累计和
SQL Server - Reverse Cumulative Sum
我有一笔累计金额需要冲销。我如何在 SQL 服务器中执行此操作?
示例:
+---+-------------------+-----+
| id| date|value|
+---+-------------------+-----+
| J1|2016-10-01 11:45:30| 100|
| J1|2016-10-02 11:30:30| 200|
| J1|2016-10-05 16:20:00| 400|
| J9|2016-10-06 08:35:00| 800|
| J9|2016-10-07 01:20:00| 900|
+---+-------------------+-----+
所需的数据帧:
+---+-------------------+-----+---------+
| id| date|value|non_cum_value|
+---+-------------------+-----+---------+
| J1|2016-10-01 11:45:30| 100| 0|
| J1|2016-10-02 11:30:30| 200| 100|
| J1|2016-10-05 16:20:00| 400| 200|
| J9|2016-10-06 08:35:00| 800| 400|
| J9|2016-10-07 01:20:00| 900| 100|
+---+-------------------+-----+---------+
我的代码:
select t1.id, t1.value, DIFFERENCE(t1.value) as 'cum_sum'
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.value
order by t1.id
嗯嗯。 . .您似乎想从“上一个”行中减去该值。那将是:
select t.*,
(t.value - lag(t.val) over (order by date)) as diff
from @t;
我不知道为什么你的标题中有“累计总和”。这并不能帮助我理解你想要做什么。
另一种可能性是:
SELECT *, V - SUM(V) OVER(ORDER BY D ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
FROM T
假设测试数据为:
CREATE TABLE T (ID CHAR(2), D DATE, V FLOAT);
INSERT INTO T VALUES
('J1', '2016-10-01 11:45:30', 100),
('J1', '2016-10-02 11:30:30', 200),
('J1', '2016-10-05 16:20:00', 400),
('J9', '2016-10-06 08:35:00', 800),
('J9', '2016-10-07 01:20:00', 900);
我有一笔累计金额需要冲销。我如何在 SQL 服务器中执行此操作?
示例:
+---+-------------------+-----+
| id| date|value|
+---+-------------------+-----+
| J1|2016-10-01 11:45:30| 100|
| J1|2016-10-02 11:30:30| 200|
| J1|2016-10-05 16:20:00| 400|
| J9|2016-10-06 08:35:00| 800|
| J9|2016-10-07 01:20:00| 900|
+---+-------------------+-----+
所需的数据帧:
+---+-------------------+-----+---------+
| id| date|value|non_cum_value|
+---+-------------------+-----+---------+
| J1|2016-10-01 11:45:30| 100| 0|
| J1|2016-10-02 11:30:30| 200| 100|
| J1|2016-10-05 16:20:00| 400| 200|
| J9|2016-10-06 08:35:00| 800| 400|
| J9|2016-10-07 01:20:00| 900| 100|
+---+-------------------+-----+---------+
我的代码:
select t1.id, t1.value, DIFFERENCE(t1.value) as 'cum_sum'
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.value
order by t1.id
嗯嗯。 . .您似乎想从“上一个”行中减去该值。那将是:
select t.*,
(t.value - lag(t.val) over (order by date)) as diff
from @t;
我不知道为什么你的标题中有“累计总和”。这并不能帮助我理解你想要做什么。
另一种可能性是:
SELECT *, V - SUM(V) OVER(ORDER BY D ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
FROM T
假设测试数据为:
CREATE TABLE T (ID CHAR(2), D DATE, V FLOAT);
INSERT INTO T VALUES
('J1', '2016-10-01 11:45:30', 100),
('J1', '2016-10-02 11:30:30', 200),
('J1', '2016-10-05 16:20:00', 400),
('J9', '2016-10-06 08:35:00', 800),
('J9', '2016-10-07 01:20:00', 900);