I need a query to transform a table from tab A to Table B: I used windowing function like Lag but it couldn't help table 1:
Concat_date_hour | Type | Value | Next_Movement |
---|---|---|---|
2021092414 | D | 16923 | 63 |
2021092415 | D | 0 | 149 |
2021092415 | D | 0 | -56 |
2021092415 | D | 0 | -131 |
2021092415 | D | 0 | -79 |
Output table:
Concat_date_hour | Type | Actual Value | New value |
---|---|---|---|
2021092414 | D | 16923 | 16986 |
2021092415 | D | 16986 | 17135 |
2021092415 | D | 17135 | 17079 |
2021092415 | D | 17079 | 16948 |
2021092415 | D | 16948 | 16869 |
PS type can be different from D
As an ordering column is missing in the source table it will be created on the fly. Other parts of the query depend on that rn
arbitrary ordering column.
select Concat_date_hour, Type,
--rn, Value, Next_Movement,
rt - Next_Movement actual, rt [new value]
from (
select *, sum(Value + Next_Movement) over (partition by Type order by Concat_date_hour, rn) rt
from (
select *, row_number() over(partition by Type, Concat_date_hour order by Concat_date_hour) rn
from tbl ) t
) t
order by Type, Concat_date_hour, rn;
db<>fiddle Note the extra row added to the original sample data.
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.