考虑我有以下一组数据
s_date | sales
------------+-------
2020-08-04 | 10
2020-08-05 | 20
2020-08-07 | 10
2020-08-08 | 20
2020-08-09 | 10
2020-08-10 | 30
2020-08-11 | 20
2020-08-12 | 10
我想计算一下每周"销售额"的平均值。请注意,缺少2020-08-03和2020-08-06日期的数据,这些数据是从2020-08-003开始的一周。
当我使用AVG((函数计算周平均值时,它会根据可用记录计算平均值。
以下是我正在尝试的查询和我从中得到的回复。
select trunc(date_trunc('WEEK', s_date)::timestamp) as week, avg(sales)
from test_temp.sales group by week;
结果:
week | avg
------------+-----
2020-08-03 | 14
2020-08-10 | 20
但是,我想计算平均值,将0作为丢失日期的值。因此,应该使用以下值进行平均计算。
s_date | sales
------------+-------
2020-08-03 | 0
2020-08-04 | 10
2020-08-05 | 20
2020-08-06 | 0
2020-08-07 | 10
2020-08-08 | 20
2020-08-09 | 10
2020-08-10 | 30
2020-08-11 | 20
2020-08-12 | 10
预期结果:
week | avg
------------+-----
2020-08-03 | 10 // Expected value
2020-08-10 | 20
有人能告诉我如何计算平均值吗?
问候,
Paul
取和除以7:
select trunc(date_trunc('WEEK', s_date)::timestamp) as week, sum(sales) / 7
from test_temp.sales
group by week;
编辑:
为了应对上周的情况,你可以这样做:
select trunc(date_trunc('WEEK', s_date)::timestamp) as week,
sum(sales) / least(7, current_date - trunc(date_trunc('WEEK', s_date)::timestamp))
from test_temp.sales
group by week;