select a, b, Volume
case
when lag(a, 1) over(order by b asc) < a then lag(c, 1) over(order by b asc) + Volume
when lag(a, 1) over(order by b asc) > a then lag(c, 1) over(order by b asc) - Volume
end as c
from Table
So what I would like to achieve her is... if previous a
row bigger/less then current a
row then add/substract Volume
from previous row c
.
if a > previous ac = previous c + Volume
if a < previous ac = previous c - Volume
But... There is no c
row because this is what I am calculating (so row c
's initial value is 0 or NULL) ... there is no pre defined set of data in c
. One data coming from another... kind of.
If I would have to write this in another language I would store the value of c
in a separate variable like previousRow
and would rewrite it with each iteration.
Can I achieve similar thing in TSQL?
Sample Data:
a | b | Volume | c |
---|---|---|---|
1 | 2020-01 | 10 | 0 |
2 | 2020-02 | 20 | 20 |
5 | 2020-03 | 40 | 60 |
3 | 2020-04 | 30 | 30 |
1 | 2020-05 | 10 | 20 |
column c pretty much boils down to a conditional rolling sum, unfortunately, sql server doesn't allow for nesting of window functions, so a derived table to establish the previous a value is necessary. After that, sum case when and you should have what you're looking for.
Try this (added additional test values to the set provided above):
SELECT
T.*,
SUM(
(
CASE
WHEN T.LAG_A IS NULL
THEN 0
WHEN T.A > T.LAG_A
THEN T.VOLUME
ELSE (T.VOLUME*-1)
END
)
) OVER (ORDER BY T.B ASC) AS C
FROM
(
SELECT
MY_TABLE.A,
LAG(MY_TABLE.A, 1) OVER (ORDER BY MY_TABLE.B ASC) AS LAG_A,
MY_TABLE.B,
MY_TABLE.VOLUME
FROM
(VALUES (1,CAST('1/1/2021' AS DATE),10),
(2,CAST('1/2/2021' AS DATE),20),
(5,CAST('1/3/2021' AS DATE),40),
(3,CAST('1/4/2021' AS DATE),30),
(1,CAST('1/5/2021' AS DATE),10),
(8,CAST('1/6/2021' AS DATE),50),
(4,CAST('1/7/2021' AS DATE),70)
) AS MY_TABLE(A,B,VOLUME)
) T
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.