Pregunta

I'm trying to avoid a cursor in TSQL when doing some rolling calculations to wages over time. Bascially I've all the data to calculate the wage but I'm trying to avoid doing it RBAR.

Given:

DROP TABLE #SampleData

SELECT *
INTO #SampleData
FROM
(
SELECT '01/01/2010' AS WageDate, 10.00 AS BaseWage, 0.05 AS WageIncrease
UNION all
SELECT '01/01/2011' AS WageDate, 10.00 AS BaseWage, 0.25 AS WageIncrease
UNION ALL 
SELECT '01/01/2012' AS WageDate, 10.00 AS BaseWage, 0.00 AS WageIncrease
UNION All
SELECT '01/01/2013' AS WageDate, 10.00 AS BaseWage, 0.15 AS WageIncrease
) data

-- Starting Point
SELECT  * ,
BaseWage * WageIncrease AS IncreaseAmount, BaseWage + (BaseWage * WageIncrease)
FROM    #SampleData

/*
Goal Point
-------------
WageDate    BaseWage    WageIncrease    IncreaseAmount
01/01/2010  10.00       0.05            0.5000
01/01/2011  10.50       0.25            2.5000
01/01/2012  13.125      0.00            0.0000
01/01/2013  13.125      0.15            1.5000
*/

Thoughts on how to proceed?

¿Fue útil?

Solución

In SQL Server 2012, you would just use a cumulative sum function:

SELECT  *,
       BaseWage * WageIncrease AS IncreaseAmount,
       BaseWage * exp(sum(log(1 + WageIncrease)) over (order by WageDate))
FROM    #SampleData

This implements a product aggregation function using logs and exponentiation.

In earlier versions, you can do the same thing with a correlated subquery:

SELECT  *,
       BaseWage * WageIncrease AS IncreaseAmount,
       (select sd.BaseWage * exp(sum(log(1 + sd1.WageIncrease))) 
        from #SampleData sd1
        where sd1.WageDate <= sd2.WageDate
       )
FROM    #SampleData sd;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top