首页 > 解决方案 > 使用 SQL 计算更新查询中的累积值

问题描述

我有以下数据库表:

Date        Return  Index
01-01-2020  0.1     Null 
01-02-2020  0.2     Null
01-03-2020  0.3     Null

我想使用以下公式更新索引值:

Index = (100 * Return) + Previous_Month_Index (if Previous_Month_Index is not available, use 100)

预期结果:(按日期升序计算的索引)

Date        Return  Index
01-01-2020  0.1     110  -- (100 + 10)
01-02-2020  0.2     130  -- (110 + 20)
01-03-2020  0.3     160  -- (130 + 30)

如何使用 SQL 做到这一点?我目前正在使用光标来计算这个,但它不是一个推荐的计算方法。

标签: sqlsql-servertsql

解决方案


要实现现有表的更新,您需要构建结果并连接回您的表以更新它。我在date这里使用您的示例加入,但您可能有一个应该使用的正确密钥:

with r as (
    select [date] , 100+Sum([return]*100) over(order by [date]) [index]
    from t
)
update t set
    t.[index]=r.[index]
from r join t on t.[date]=r.[date]

推荐阅读