mysql - 如何获得一年内最多五个连续值?

标签 mysql sql

我有过去 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/

相关文章:

INSERT INTO 语句中的 PHP 语法错误。SQLExecDirect 中的 SQL 状态 37000

sql - APOSTROPHE 里面的 xml 元素值

java - :Noob Alert: How can users in the same database add each other to their 'contact lists' ?

php - 是否可以显示 'Session User"

php - img src 不适用于 php 和 php 变量

mysql - 查询速度的巨大差异

php - 来自数据库的 Unix_Timestamp

php - 如何获取某个类别的产品标签?

php - 如何使用命令sql在php中随机获取10行

php - 如何在 mySql 上加入 2 个表?