Running total over date range - fill in the missing dates

前端 未结 4 1069
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 03:05

I have the following table.

DATE  | AMT
10/10 | 300
12/10 | 300
01/11 | 200
03/11 | 100

How do I get the monthly total? A result like -

4条回答
  •  温柔的废话
    2021-01-15 03:49

    You can also generate a range on the fly, pass its value as the interval to DATE_ADD, and basically project a sequence of month values.

    As @Dems said, you need to have a correlated subquery calculate the running total, which will be very inefficient, because it will run a nested loop internally.

    To see how to generate the sequence, check my post here: How to generate a range of numbers in Mysql

    The end query should look something like this: (Incidentally, you should have a date column, not this varchar mess).

    /*NOTE: This assumes a derived table (inline view) containing the sequence of date values and their corresponding TOT value*/
    SELECT
      DATEVALUES.DateValue,
      (
      SELECT SUM(TABLE1.AMT) FROM TABLE1 WHERE TABLE1.DateValue <= DATEVALUES.DateValue)
      ) AS RunningSubTotal
    FROM
      DATEVALUES
    

    Or something like that.

提交回复
热议问题