简体   繁体   中英

SQL multiplying based on previous calculated row record

I have created the below query and am trying to have another column that has an initial value of 1000 in the last row and then multiplies original 1000 by the mdp.DataPointValue and then after the initial 1000 uses the newly calculated value going forward.

For example, on 5/25/10 I would like the starting value to be 1000. On 5/26/10 I would like it to be mdp.DataPointValue * Previous Value (1000 for the first one) and so on. Any help would be much appreciated

SELECT        AsOfDate, 
              mdp.DataPointValue
FROM           DataPointPITs AS mdp
WHERE        mdp.DataPointId = '2710' AND AsOfDate > '2010-05-25'
ORDER BY     AsOfDate DESC

This sounds like a job for LAG()

SELECT        AsOfDate, 
              mdp.DataPointValue,
              mdp.DataPointValue * LAG(mdf.DataPointValue, 1, 1000) OVER (ORDER BY AsOfDate DESC) 
FROM           DataPointPITs AS mdp
WHERE        mdp.DataPointId = '2710' AND AsOfDate > '2010-05-25'
ORDER BY     AsOfDate DESC

Welcome to the wonderful wacky world of windowing functions.

Assuming the values are always positive (never negative or zero) and have no gaps, you can do a cumulative product using SUM() and arithmetic:

SELECT AsOfDate, mdp.DataPointValue,
       1000 * exp(sum(log(mdp.DataPointValue)) over (order by AsOfDate))
FROM  DataPointPITs mdp
WHERE mdp.DataPointId = '2710' AND AsOfDate > '2010-05-25'
ORDER BY AsOfDate DESC;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM