【问题标题】:Calculate cumulative value in update query using SQL使用 SQL 计算更新查询中的累积值
【发布时间】:2021-04-28 09:47:13
【问题描述】:

我有以下数据库表:

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 来做到这一点?我目前正在使用光标来计算这个,但它不是一个推荐的计算方式。

【问题讨论】:

  • 这能回答你的问题吗? How to get cumulative sum
  • @Larnu - 谢谢,在这种情况下我需要更新表中的值。
  • 但这并没有改变解决方案。如第二个答案所示,您仍然需要窗口化的SUM
  • 另外,我需要以100为起点。你有查询的例子吗?谢谢。
  • 那么你想要 Stu 的答案只是没有更新(即 CTE 中有什么!)

标签: sql sql-server tsql


【解决方案1】:

要实现现有表的更新,您需要构建结果并连接回您的表以更新它。我在这里使用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]

【讨论】:

  • 谢谢@Stu。无论如何要实现 Index = (Previous_Month_Index * Return) + Previous_Month_Index 。第一个月,Previous_Month_Index 为 100。
  • @developer 。 . .这不是最好的解决方案。不需要join
  • 感谢@GordonLinoff,不幸的是我必须删除这个问题。我在这里发布了另一个问题:stackoverflow.com/questions/67299495/…
  • 我同意 Gordon 的建议是首选且更简洁 - 我总是忘记您可以在 CTE 中更新
  • @developer 。 . .没有理由删除这个问题。
【解决方案2】:

你想要一个累积的总和。在 SQL Server 中,您应该使用可更新的 CTE:

with toupdate as (
      select t.*,
            100+Sum(return * 100) over (order by date) as new_index
      from t
     )
update toupdate
    set index = new_index;

请注意,dateindexreturn 等列名称是非常糟糕的选择,因为它们是 SQL 关键字。我没有在上述逻辑中转义它们(我认为转义的名称只是杂乱的查询)。我希望您在实际的表格中有更好的命名约定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 2019-11-16
    相关资源
    最近更新 更多