【问题标题】:How to calculate the value from the previous date to uptodate如何计算从上一个日期到更新的值
【发布时间】:2021-08-13 04:31:45
【问题描述】:

我想计算previous_date 到up_to_date 的值。请参阅下面的示例表。

month participant total participant
2021-07 6 6
2021-08 5 11
2021-09 20 31

假设我们在 2021 年 7 月有 6 个参与者,总参与者等于 6。那么在 2021 年 8 月我们有 5 个参与者,它将添加上个月(总参与者)和当前的两个值。应该是 11,因为 6 + 5 = 11。那么到 2021 年 9 月,我们有 20 名参与者,所以总参与者(11)+参与者(20)=总参与者(31)

【问题讨论】:

  • 可能是sum(participant) 会帮助你。

标签: mysql sql


【解决方案1】:

这是“累计”。

对于 MySQL 8+ 使用窗口函数:

SELECT `month`,
       participant,
       SUM(participant) OVER (ORDER BY `month`) `total participant`
FROM test;

对于 MySQL 5.x,使用 2 个表副本:

SELECT t1.`month`,
       t1.participant,
       SUM(t2.participant) `total participant`
FROM test t1
JOIN test t2 ON t1.`month` >= t2.`month`
GROUP BY t1.`month`,
         t1.participant;

https://dbfiddle.uk/?rdbms=mysql_8.0&rdbms2=mysql_5.7&fiddle=0f0152e44e18a57af8955fd4f7d881e2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2021-12-19
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多