Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Using calculated result from previous row

$
0
0

Hi,

I am not sure if this is possible as I haven't found a solution yet online.  In short I have a table with some values such as:

UniqueRowNo    Value 

1                        5

2                        10

3                        15

4                        20

5                        30

I would like to get the below table.  It essentially, uses the current Value * previous Result

UniqueRowNo    Value    Result

1                       5          5

2                       10        50

3                       15        150      

4                       20        3000

5                       30        90000

I have tried below query but it does not work:

SELECT currB.rowNo AS currRow, currB.Value AS currValue,
	CASE
		WHEN currB.rowNo = 1 THEN currB.Value * 1
		WHEN currB.rowNo = 2 THEN currB.Value * prevB.Value
		ELSE currB.Value * (prevB.Value * prevPrevB.Value)
	END AS Result	
FROM @tmpTable AS currB
	LEFT JOIN @tmpBloomberg AS prevB ON currB.rowNo = prevB.rowNo+1
	LEFT JOIN @tmpBloomberg AS prevPrevB ON currB.rowNo = prevPrevB.rowNo+2

It does not work because I am using the values from previous 2 values.  What I need is to get the previous Result.  So that I can calculate the previous Result with the current Value.

Can anyone suggest the solution please ?




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>