簡體   English   中英

在上一行內的相同計算值上創建計算值

[英]Create Calculated Value On Same Calculated Value Inside Previous Row

我正在嘗試根據此表使用 SQL 制作一個腳本來計算“SHI”列。

| 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 |

我需要使用以下方法計算 SHI 列:

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

需要明確的是,我的數據中尚不存在 SHI 列。 這就是我試圖讓我的查詢計算的內容。 我的問題是,我不知道如何將之前的 SHI 值插入到當天的公式中。

知道如何在 SQL 中創建它嗎?

使用 cte,您可以達到您想要的結果。

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:

在此處輸入圖像描述

如果行數超過 100,則使用OPTION (MAXRECURSION xxx)設置更大的遞歸限制,最高可達 32,767,如下所示:

    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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM