I have a table with this data:
create table my_table (
month varchar(2),
services integer null,
s_registered integer,
s_terminated integer
);
insert into my_table(month, services, s_registered, s_terminated) values
('01', 395, 14, 14),
('02', null, 5, 9),
('03', null, 19, 15),
('04', null, 30, 11),
('05', null, 13, 15),
('06', null, 8, 11),
('07', null, 10, 17),
('08', null, 13, 17),
('09', null, 5, 10),
('10', null, 10, 19),
('11', null, 7, 22),
('12', null, 18, 13);
You can see the services
column and I need a query to select the result with the calculated services
in each row.
The services
column is equal to services + s_registered - s_termination
of the previous row.
I tried using the window cte LAG() function, but it only worked once. It correctly accepts the first services
column, but on the next iteration the LAG takes the column as null.
I think this issue can be resolved with recursive CTE, do you have any ideas?:)
2
Answers
You can indeed do this with a recursive CTE. For example, you could use this as a base and customise it for your needs:
You do not want a recursive cte for this, you can simply use the SUM window function: