简体   繁体   中英

Create Calculated Value On Same Calculated Value Inside Previous Row

I'm trying to make a script to calculate "SHI" Column using SQL based on this table.

| Day | BR  | BR2 | HI  |  SHI   |
----------------------------------
|  1  | 0   |  0  | 0   |  0     |
|  2  | 400 | 400 | 95  |  95    |
|  3  | 0   | 400 | 0   |  95    |
|  4  | 350 | 750 | 100 |  97.33 |
|  5  | 350 |1100 | 100 |  98.18 |

I need to calculate the SHI Column using:

SHI  =  ((BR * HI) + (Prev.SHI * Prev.BR2)) / BR2

Just to be clear, the SHI Column do not exist in my data yet. That is what I am trying to have my query calculate. My problem is, I don't know how to get the previous SHI Value to insert on that formula for current day.

Any idea how to create this in SQL?

With cte you can achieve your desired result.

with cte as 
(
select day,br,br2,hi,(case when br2<>0 and br2 is not null then coalesce(round( ((br*hi))/br2,2),0) else 0 end)SHI from S66312677V2 where day=1
union all 
select s.day,s.br,s.br2,s.hi,
(case when s.br2<>0 and s.br2 is not null then coalesce(round( ((s.br*s.hi)+cte.shi*cte.br2)/s.br2,2),0) else 0 end)SHI from S66312677V2 s
inner join cte on s.day-1=cte.day
where s.day<>1
)
select * from cte

Output:

在此处输入图像描述

If number of rows is more than 100 then use OPTION (MAXRECURSION xxx) to set a larger recursion limit up-to 32,767 as below:

    with cte as 
        (
        select day,br,br2,hi,(case when br2<>0 and br2 is not null then coalesce(round( ((br*hi))/br2,2),0) else 0 end)SHI from S66312677V2 where day=1
        union all 
        select s.day,s.br,s.br2,s.hi,
        (case when s.br2<>0 and s.br2 is not null then coalesce(round( ((s.br*s.hi)+cte.shi*cte.br2)/s.br2,2),0) else 0 end)SHI from S66312677V2 s
        inner join cte on s.day-1=cte.day
        where s.day<>1
        )
        select * from cte
OPTION (MAXRECURSION 999)

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