使用Postgres插入其他行

时间:2020-09-21 11:16:36

标签: sql postgresql

我正在尝试编写查询以获取每天的总销售额,结果应包含所有日期 从2020-05-01到当前日期,无论该日期是否为 出售与否。 下面的查询将提供表中相应日期的销售结果。

select date as DATE, SUM (order_amount_in_eur) 
from orders 
where date >= '2020-05-01' group by 1;

我希望从2020-05-01到今天为止的其他日期行在表中不存在,并且在相应日期的销售列中将零值设置为零/不销售。 我希望从附件屏幕快照中得到以下答案,以查找从2020-05-01开始的所有遗漏日期。

谢谢

EX:enter image description here

这是我的原始桌子。

enter image description here

1 个答案:

答案 0 :(得分:1)

您将使用left joingenerate_series()

select gs.dte, coalesce(sum(order_amount_in_eur), 0)
from generate_series('2020-05-01'::date, current_date, interval '1 day') gs(dte) left join
     orders o
     on o.date = gs.dte
group by gs.dte;
相关问题