我有一张表格,其中有2列已访问并且已付款
visited amount paid
-------------------------
2018-04-01 100
2018-04-02 200
2018-04-03 300
我想获取最近7天(今天和过去6天)的平均付款额以及访问量和结果中支付的金额:
输出:
visited amount average of last 7 days
---------------------------------------------------
2018-04-01 100 100
2018-04-02 200 150
2018-04-03 300 200
说明:
Row 1 : average amount = 100/1 = 100
Row 2 : average amount = (100 + 200)/2 = 150
Row 3 : average amount = (100 + 200 + 300)/3 = 200
我正在使用MySQL或Oracle数据库尝试此操作,一切正常。
答案 0 :(得分:1)
您需要在MySQL 5.x中使用相关子查询:
SELECT visited, amount_paid, (
SELECT AVG(amount_paid)
FROM t AS x
WHERE x.visited >= t.visited - INTERVAL 6 DAY
AND x.visited <= t.visited
) AS 7_day_avg
FROM t
在MySQL 8和Oracle中,您可以使用窗口函数。
答案 1 :(得分:1)
对于具有AVG()
分析功能的Oracle:
select t.*, avg(t."amount paid") over (order by t."visited") as "average of last 7 days"
from tablename t
where t."visited" >= to_date('08-11-2019', 'dd-MM-yyyy') - 7
and t."visited" <= to_date('08-11-2019', 'dd-MM-yyyy')
请参见demo。
答案 2 :(得分:1)
如果我理解正确,则需要累积的运行平均值。如果是这样,您可以使用窗口功能:
select t.*
avg(amount_paid) over (order by visited
range between interval '6' day preceding and current row
)
from t;
Oracle和MySQL 8+均支持此语法。