SQL查找达到特定阈值的连续天数

时间:2016-10-26 14:51:04

标签: sql postgresql

我有两列; the_day和amount_raised。我想找到至少100万美元筹集的连续天数。我能在SQL中执行此操作吗?理想情况下,我想创建一个计算连续天数的列,然后如果未达到100万美元的阈值则重新开始。

到目前为止我所做的是创建第三列,如果达到100万,则将1放入行中。我可以创建一个子查询并计算列出的连续1,然后在它达到0时重置吗? enter image description here

,这是所需的输出

enter image description here

2 个答案:

答案 0 :(得分:1)

select dt,amt,
case when amt>=1000000 then -1+row_number() over(partition by col order by dt) 
else 0 end col1
from (select *, sum(case when amt >= 1000000 then 0 else 1 end) over(order by dt) col 
      from t) x

Sample Demo

答案 1 :(得分:0)

SELECT the_day,
       amount_raised,
       million_threshold,
       CASE WHEN million_threshold <> lag_million_threshold AND million_threshold = lead_million_threshold
            THEN 1
            WHEN million_threshold = lag_million_threshold
            THEN SUM(million_threshold) OVER ( ORDER BY the_day ROWS UNBOUNDED PRECEDING )
            ELSE 0
        END AS consecutive_day_cnt          
  FROM
     (
       SELECT  the_day, 
               amount_raised,
               million_threshold,
               LAG(million_threshold,1) OVER ( ORDER BY the_day ) AS lag_million_threshold,
               LEAD(million_threshold,1) OVER ( ORDER BY the_day ) AS lead_million_threshold
         FROM
            ( 
              SELECT  the_day,
                      amount_raised,
                      CASE WHEN amount_raised >= 1000000
                           THEN 1
                           ELSE 0
                       END AS million_threshold
                 FROM Yourtable
            )
      );