Forum Discussion
Anonymous
4 years agoNot applicable
For each group find first negative value and replace subsequent years with zero
Hello, how can I get the first negative number for each Group, Category and Country and then make the new value for that year and years after value zero? Group Category Country Year Value ...
smpa01
Community Champion
4 years agoAnonymous are you getting it from a SQL server? If there is no filter context involved for this task, doing the transformation server side will give you the optimimum performnace.
For example, in TSQL
declare @t1 as table (grp int,cat varchar(10), country int, year int, value int, row int)
insert into @t1
select
*
from
(
values
(1, 'A', 1, 2018, 50, 1),
(1, 'A', 1, 2019, 20, 2),
(1, 'A', 1, 2020,-10, 3),
(1, 'A', 1, 2021, 20, 4),
(1, 'B', 1, 2018, 50, 5),
(1, 'B', 1, 2019,-20, 6),
(1, 'B', 1, 2020,-10, 7),
(1, 'B', 1, 2021, 20, 8)
) t(a, b, c, d, e, f);
with cte1 as(
select
grp, cat, country, year, value, row,
CASE when sum(value) over ( partition by grp, cat, country, year )< 0 then 0 else null end as _helper
from @t1
)
select
grp, cat, country, year, value, row,
CASE WHEN max(_helper) over(partition by grp, cat, country order by year rows unbounded preceding ) IS NULL then value
else max(_helper) over (partition by grp, cat, country order by year rows unbounded preceding ) end as Desired
from cte1
order by row