我有一张表格如下
Day_No Average Count
------ -------- ------
1 7.5 12
2 12 15
3 15 4
4 13 14
5 6.5 12
6 21 17
7 15 4
8 11 15
9 15 11
10 10 13
11 9 40
12 13 12
.
.
.
.
.
我想生成7天移动平均线。我已经看到每天都有相同权重的解决方案,但显然每个平均需要根据计数进行加权。有什么建议吗?
答案 0 :(得分:4)
我不完全确定你想要达到的目标。也许这就是你想要的:
select day_no,
average,
cnt,
avg(average * cnt) over (order by day_no rows between 7 preceding and current row) as running_avg
from data
order by day_no;
rows between 7 preceding and current row
子句假定结果中每天有一行。
(请注意,我对cnt
列使用了count
,因为使用保留字作为列名称不是一个好主意。)
SQLFiddle示例:http://sqlfiddle.com/#!4/fa0a84/1
答案 1 :(得分:1)
解决!需要将平均值和计数的乘积相加,然后除以范围内的计数。
select day_no,
average,
cnt,
sum(average * cnt) over (order by day_no rows between 7 preceding and current row)/sum(cnt) over (order by day_no rows between 7 preceding and current row) as running_avg
from data
order by day_no;
感谢horse_with_no_name让我走上正轨
答案 2 :(得分:0)
select initial_data.full_sum/initial_data.fullCount as the_avg
from
(select
sum(Average * count) as full_sum,
sum(count) as full_count
from the_table
group by <the grouping condition>) initial_data
像这样的东西。不记得所有组和算术的正确oracle语法
答案 3 :(得分:0)
我会尝试以下查询:
select Day_No day,
(select sum(Average*Count)/sum(Count)
from table
where Day_No between day-7 and day)
from table;