Month | Value1 | data | Excel formula
---------+---------+---------+--------------
March-19 | 30 (B2) | 30 (C2) | = (B2)-sum(0)
April-19 | 30 (B3) | 0 (C3) | = (B3)-sum(C2)
May-19 | 30 (B4) | 0 (C4) | = (B4)-sum(C2:C3)
June-19 | 30 (B5) | 0 (C5) | = (B5)-sum(C2:C4)
We need to calculate the c column that is DATA column. Formula for calculating the data column is present in Excel formula. Any cell value of data column == (is value of a fixed column- sum of all the previous values of that calculated column).
Basically we need to use CTE recursive with the sum function.
How can we do that?
I don't think that you need recursion here, window functions should do it:
select
t.*,
value1 - sum(data) over(
order by month
rows between unbounded preceding and 1 preceding
) res
from mytable t
This assumes that you are storing dates in the month
column in a date
-like datatype (or at least in a string format that is properly sortable).
We can also express the query as follows, without a range clause:
select
t.*,
value1 + data - sum(data) over(order by month) res
from mytable 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.