我正在处理一个有订单的订单系统。对于分析部门,我想构建一个视图,该视图可以累积给定日期的所有销售额。
这不是问题,我得到了有效的查询。更复杂的是第二个数字,我想显示当天的累计销售额。
表示如果我在2月1日的销售额为$ 100,则该列应显示为$ 100。如果2月2日的销售额为$ 200,则该列应显示$ 300,依此类推。
这是我到目前为止提出的:
select
date_trunc('day', o.created_at) :: date,
sum(o.value) sales_for_day,
count(o.accepted_at) as num_of_orders_for_day,
-- sales_for_month_to_date
-- num_of_orders_for_month_to_date
from
orders o
where
status = 'accepted'
group by
date_trunc('day', o.accepted_at);
答案 0 :(得分:1)
只需使用窗口功能:
select date_trunc('day', o.created_at) :: date,
sum(o.value) as sales_for_day,
count(o.accepted_at) as num_of_orders_for_day,
sum(sum(o.value)) over (partition by date_trunc('month', o.accepted_at order by min(o.created_at)) as sales_for_month_to_date
sum(count(*)) over (partition by date_trunc('month', o.accepted_at order by min(o.created_at)) as num_of_orders_for_month_to_date
from orders o
where status = 'accepted'
group by date_trunc('day', o.accepted_at);
根据您代码中的注释,我推测您需要最新的数字,因此这也会按月划分。