40 - 餐馆营业额变化增长
-- 方法一
SELECT
t.visited_on,
sum(c.amount) amount,
ROUND(sum(c.amount) / 7, 2) average_amount
FROM
customer c,
-- 查出足够7天的数据日期
(SELECT DISTINCT
visited_on
FROM
customer
WHERE
visited_on >=(SELECT ADDDATE(MIN(visited_on), 6) FROM customer)) t
WHERE
c.visited_on BETWEEN SUBDATE(t.visited_on, 6) AND t.visited_on
GROUP BY
t.visited_on;
-- 方法二
SELECT visited_on,
amount,
round(amount / 7, 2) average_amount
FROM (
SELECT DISTINCT
visited_on,
SUM(amount) OVER (ORDER BY visited_on RANGE INTERVAL 6 DAY PRECEDING) amount
FROM
customer
) t
WHERE
-- 当前日期比最小值多6天及以上
visited_on >=(SELECT ADDDATE(MIN(visited_on), 6) FROM customer);
-- 方法三
select
visited_on,sum_amount as amount,round(average_amount,2) as average_amount
from
# 分组的数据进行7日分组
(
select
visited_on,
sum(amount) over (order by visited_on rows 6 preceding) sum_amount,
avg(amount) over (order by visited_on rows 6 preceding) average_amount
from
# 根据日期分组
(
select
visited_on,sum(amount) as amount
from
Customer
group by
visited_on
)t1
)t2
where datediff(visited_on,(select min(visited_on) from Customer))>=6