0

我需要一个查询来返回当月每天所有已付账单的累计总和。

我尝试了一些代码,包括这个:

SELECT DISTINCT 
         month.day,
         sum(bills.value) OVER (ORDER BY month.day)
FROM generate_series(1,31) month(day)
  LEFT JOIN bills ON date_part('day',bills.payment_date) = month.day
WHERE
(
(date_part('year',bills.payment_date)=date_part('year',CURRENT_DATE)) AND
(date_part('month',bills.payment_date)=date_part('month',CURRENT_DATE))
)
GROUP  BY month.day, bills.value, bills.payment_date
ORDER  BY month.day

我越来越:

day  | value  
1    |  1000   
4    |  3000   
5    |  5000

总和是正确的,但我没有从 generate_series 函数中得到全部 31 天。此外,当我删除 DISTINCT 命令时,查询只会重复几天,例如:

day  | value  
1    |  1000   
4    |  3000   
4    |  3000  
4    |  3000  
4    |  3000  
5    |  5000   
5    |  5000   

我想要的是:

day  | value  
1    |  1000   
2    |  1000   
3    |  1000  
4    |  3000  
5    |  5000  
6    |  5000   
...  |  5000   
31   |  5000  

有任何想法吗?

4

1 回答 1

0

从 group by 中删除bills.value, bills.payment_date,然后您也不再需要 distinct 了。您还可以简化 WHERE 子句。但是您需要将该条件移动到 JOIN 条件中,否则它将把外部联接转回内部联接。

SELECT month.day,
       sum(sum(bills.value)) over (order by month.day) as total_value
FROM generate_series(1,31) month(day)
  LEFT JOIN bills
        ON date_part('day',bills.payment_date) = month.day
       AND to_char(bills.payment_date, 'yyyymm') = to_char(current_date, 'yyyymm')
GROUP  BY month.day
ORDER  BY month.day
于 2019-11-06T12:32:45.563 回答