检测 SQL 中的连续日期并启动计数器
Detect consecutive dates in SQL and start counter
Dates
2021-01-01
2021-01-02
2021-01-03
2021-01-10
2021-01-11
2021-01-12
2021-01-15
预期输出:
Dates
Counter
2021-01-01
1
2021-01-02
2
2021-01-03
3
2021-01-10
1
2021-01-11
2
2021-01-12
3
2021-01-15
1
知道如何实现吗?我确实知道如何找到连续日期的最小值、最大值和计数,但需要一个计数器,每次出现日期间隔时都会重置
解决此类“缺口和孤岛”问题的一种方法是根据与前一天的差异计算排名。
然而,计算日期之间天数差异的方法取决于您的 RDBMS。
此示例使用 DATEDIFF(MS Sql 服务器)
SELECT
Dates,
ROW_NUMBER() OVER (PARTITION BY Rnk ORDER BY Dates) AS Counter
FROM
(
SELECT
Dates,
SUM(CASE
WHEN DATEDIFF(day, prevDate, Dates) = 1 THEN 0
ELSE 1 END) OVER (ORDER BY Dates) AS Rnk
FROM
(
SELECT
Dates,
LAG(Dates) OVER (ORDER BY Dates) AS prevDate
FROM your_table
) q1
) q2
ORDER BY Dates;
你可以使用自join
:
with cte as (
select row_number() over (order by dt) r, dt from test
)
select c.dt, sum(c.dt = date_add(c1.dt, interval c.r-c1.r day))
from cte c join cte c1 on c1.r <= c.r group by c.dt order by c.dt
Dates |
---|
2021-01-01 |
2021-01-02 |
2021-01-03 |
2021-01-10 |
2021-01-11 |
2021-01-12 |
2021-01-15 |
预期输出:
Dates | Counter |
---|---|
2021-01-01 | 1 |
2021-01-02 | 2 |
2021-01-03 | 3 |
2021-01-10 | 1 |
2021-01-11 | 2 |
2021-01-12 | 3 |
2021-01-15 | 1 |
知道如何实现吗?我确实知道如何找到连续日期的最小值、最大值和计数,但需要一个计数器,每次出现日期间隔时都会重置
解决此类“缺口和孤岛”问题的一种方法是根据与前一天的差异计算排名。
然而,计算日期之间天数差异的方法取决于您的 RDBMS。
此示例使用 DATEDIFF(MS Sql 服务器)
SELECT
Dates,
ROW_NUMBER() OVER (PARTITION BY Rnk ORDER BY Dates) AS Counter
FROM
(
SELECT
Dates,
SUM(CASE
WHEN DATEDIFF(day, prevDate, Dates) = 1 THEN 0
ELSE 1 END) OVER (ORDER BY Dates) AS Rnk
FROM
(
SELECT
Dates,
LAG(Dates) OVER (ORDER BY Dates) AS prevDate
FROM your_table
) q1
) q2
ORDER BY Dates;
你可以使用自join
:
with cte as (
select row_number() over (order by dt) r, dt from test
)
select c.dt, sum(c.dt = date_add(c1.dt, interval c.r-c1.r day))
from cte c join cte c1 on c1.r <= c.r group by c.dt order by c.dt