我有过去 20 年某种商品的年度销售列表。
数据是这样的。
date ; sales value
2001-01-01 ; 423
2001-01-02 ; 152
2001-01-03 ; 162
2001-01-04 ; 172
.
.
.
我有行为问题。我必须找到过去 20 年中每年销售额总和最大的连续五天。然后使用结果我必须分析支出模式。
如何获取一年中总和最大的连续 5 天?
我必须获取所有年份的日期以及这 5 天总销售额的总和。有人可以帮我完成作业吗?
TIA
最佳答案
嗯,在 MySQL 8+ 中,您可以使用窗口函数。在早期版本中,是相关子查询。看起来像:
select year(t.date),
max(next_5_days_sales),
substring_index(group_concat(date order by next_5_days_sales desc), ',', 1) as date_at_max
from (select t.*,
(select sum(t2.sales)
from t t2
where t2.date >= t.date and t2.date < t.date + interval 5 day
) as next_5_days_sales
from t
) t
group by year(t.date);
注释:
- 您需要重置 group_concat_max_len,因为 1024 对于中间结果来说可能不够长。
- 这允许期间跨越年份边界。
在 MySQL 8 中,使用窗口函数!
select t.*
from (select t.*,
row_number() over (partition by year(date) order by next_5_days_sales) as seqnum
from (select t.*,
sum(t2.sales) over (order by date range between current row and 4 following) as as next_5_days_sales
from t
) t
) t
where seqnum = 1;
关于mysql - 如何获得一年内最多五个连续值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582503/