generate_series 的数据差距问题

Problem with gaps in data with generate_series

我需要查询returns当月所有已付账单的累计金额

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

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  

有什么想法吗?

从 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