如何排除MySQL窗口函数在日期范围内的差距?

时间:2019-05-10 12:33:12

标签: mysql sql

我每个工作日都有销售量(第四和第五个周末):

date        sales
2019-05-02  5
2019-05-03  5
2019-05-06  5
2019-05-07  10
2019-05-08  10

我想创建具有相同销售额的日期范围。但是范围不应该包括差距。所以我需要的是这个

from_date   to_date     sales
2019-05-02  2019-05-03  5
2019-05-06  2019-05-06  5
2019-05-07  2019-05-08  10

这是我当前的查询:

SELECT * FROM (
    SELECT
       MIN(date) OVER(my_window) AS from_date,
       MAX(date) OVER(my_window) AS to_date,
       sales
    FROM sales_table
    WINDOW my_window AS (
        PARTITION BY sales
    )
) AS window_query
GROUP BY from_date, to_date, sales

实现以下目标:

from_date   to_date     sales
2019-05-02  2019-05-06  5
2019-05-07  2019-05-08  10

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这是一个孤岛问题。您可以通过从日期中减去数字序列来解决该问题。连续日期将具有相同的日期:

SELECT MIN(date), MAX(date), sales
FROM (SELECT s.*,
             ROW_NUMBER() OVER (PARTITION BY sales ORDER BY date) as seqnum
       FROM sales_table s
      ) s
GROUP BY sales, date - interval seqnum day;