sql - 使用 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 做到这一点?我目前正在使用光标来计算这个,但它不是一个推荐的计算方法。
解决方案
要实现现有表的更新,您需要构建结果并连接回您的表以更新它。我在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]
推荐阅读
- akka-stream - akka 流 - 使用 conflate 时触发元素流
- xslt - 问题 - 使用变量中的值对多个 XML 文件进行 XSL 搜索
- c++11 - 如何在我的 GCC (7.3.0) 版本中激活 c++11 来安装 CMake?
- linux - Qt 5.10 QGraphicsView 无法将 QGraphicsScene 缩放到全屏
- javascript - 在父状态更改后强制在 React 上重新渲染 D3 组件
- c - 使用 void 指针对算法进行排序,我该怎么做?
- html - 如何在 NavBar 的媒体查询中居中对齐/对齐菜单项?
- python - 如何在列表理解中分配给函数调用
- javascript - 仅当用户关闭页面时如何将数据发送到服务器?
- java - 印刷宾果板,Java