给定 endDate SQL (Postgres) 的条纹

问题描述 投票:0回答:1

enter image description here

对于给定的日期,我想获得条纹(连续日期向后,其中数字高于/等于某个阈值 => 在示例中始终为 1000)

示例:

  • 输入日期2024-11-15 =>结果2
  • 日期输入 2024-11-14 => 结果1
  • 输入日期2024-11-8 => 结果0
  • 输入日期2024-11-7 =>结果3
  • 日期输入 2024-11-5 => 结果1

我将非常感谢您的帮助。非常感谢!

sql postgresql
1个回答
0
投票

最简单的是使用递归:

WITH RECURSIVE streak AS (
    SELECT 
        d.date,
        d.number,
        1 AS streak_counter
    FROM data d
    WHERE d.date = '2024-11-07'.  --> Your date here

    UNION ALL

    SELECT 
        d.date,
        d.number,
        streak.streak_counter + 1
    FROM data d
    INNER JOIN streak ON d.date = streak.date - INTERVAL '1 day'
    WHERE d.number >= 1000
)
SELECT MAX(streak_counter) FROM streak;
© www.soinside.com 2019 - 2024. All rights reserved.