SQL FIDDLE
I tried to sum the column qx
in my CTE from the current row to the last row creating a calculated column called qxsum
like the following:
declare @idade int = 25
declare @sexo char = 'm'
;with cte as (
select
@idade as idade,
@sexo as sexo,
case when @sexo = 'm' then mor.Masculino else mor.Feminino end as qx,
cast((sum(1.0) over (order by @idade rows between current row and unbounded following)) as float) as qxsum
from Mortalidade as mor
where mor.Idade = @idade
union all
select
cte.idade + 1,
cte.sexo,
mor.qx,
cast((sum(cte.qx) over (order by @idade rows between current row and unbounded following)) as float) as qxsum
from cte
outer apply (
select
case when cte.sexo = 'm' then mor.Masculino else mor.Feminino end as qx
from Mortalidade as mor
where mor.Idade = cte.Idade + 1
) mor
where cte.Idade < 120
) select * from cte option (maxrecursion 0);
For instance, for the age 25 in the SQL Fiddle above the qxsum
should be the sum from qx
from the age 25 to the age 120.
But SQL Server is returning the same value lagging one row, because I am making mistakes and I don't know which mistake I am making.