Search code examples
sqlpostgresqlpostgresql-11

Sum from date to date


I have a table with this data:

Date        Value
...
2020-07-30  0.0
2020-07-31  12527.922
2020-08-01  29983.598
2020-08-02  34333.74
2020-08-03  33550.0
...
2020-08-30  22722.02
2020-08-31  21376.416
2020-09-01  23762.43
2020-09-02  16267.47
2020-09-03  25241.0
...

I need to sum from the first day of month to the next first day of month inclusive. Ie, from 2020-08-01 to 2020-09-01 inclusive and that value being in a column for all the days of the starting period (in this case 08) Any ideas? Thanks.

Expected output:

Date        Value      Period_Sum
...
2020-07-30  0          sum of 2020-07-01 to 2020-08-01
2020-07-31  1          ...
2020-08-01  2          sum of 2020-08-01 to 2020-09-01
2020-08-02  3          ...
2020-08-03  3          ...
...
2020-08-30  2          ...
2020-08-31  2          ...
2020-09-01  2          sum of 2020-09-01 to 2020-10-01
2020-09-02  1          ...
2020-09-03  2          ...
...

Base on Adrian's reply I'm trying to make it with sub selects like:

select
  (
    select
      sum(qq.value)
    from
      data_table qq
    where
      qq.date between date_trunc('month', q.date)
      and date_trunc('month', q.date) + interval '1 month'
  ) period_sum
, date
, value
from
  data_table q

But it's missing the first day of the next month. I think I need to tweak the interval part.


Solution

  • As example:

    SELECT 
        SUM(VALUE)
    FROM
        some_table
    WHERE 
        Date BETWEEN '2020-08-01' AND '2020-09-01';