SQLite 按选定日期范围内的所有日期分组,即使数据不存在

SQLite group by all the days in selected date range even data not exsist

我有一个包含两列的 table invoicedatetotal 我想获得过去 30 天的 总计 按一个月中的所有天分组(或者最后 7 天按一周中的所有天分组)

date     total
11/16    500
11/23    200
12/2     400
12/4     600

我试过这样的东西,

SELECT strftime('%m/%d', Date) as valDay, SUM(Total) 
FROM invoice  
GROUP BY valDay 
Order By Date DESC LIMIT 30 ;

它给出了最后 30 条记录。但我想要过去 30 天的所有记录,即使 table 有几天没有数据(那几天的总数必须 return 0)

您可以使用递归查询生成日期,然后将 table 带入左连接并聚合:

with recursive cte as (
    select date('now') as dt,  date('now', '-30 day') last_dt
    union all select date(dt, '-1 day'), last_dt from cte where dt > last_dt
)
select c.dt, coalesce(sum(i.total), 0) as total
from cte c
left join invoice i on i.date >= c.dt and i.date < date(c.dt, '+1 day')
group by c.dt
order by c.dt desc