计算最大连续连续透支天数

时间:2019-07-05 11:24:37

标签: oracle select

Date  | Account |  Amount   | Count max number of day continuous < 0     |
  1   |   1001  | 100        | 0   |
  2   |   1001  | -100       | 1   |
  3   |   1001  | -100       | 2   |
  4   |   1001  | 100        | 2   |
  5   |   1001  | -100       | 2   |
  6   |   1001  | -100       | 2   |
  7   |   1001  | -100       | 3   |
  8   |   1001  | -100       | 4   |
  9   |   1001  | 100        | 4   |

我有示例数据。我想拥有“连续最大计数天数<0”列。我如何在Oracle数据库中选择它

1 个答案:

答案 0 :(得分:0)

要找到连续的时间段,可以使用Tabibitosian method。然后使用分析型count,最后使用max

select date_, account, amount, 
       max(cnt) over (partition by account order by date_) max_overdraft_period
  from (
    select date_, account, amount, 
           count(case when amount <= 0 then 1 end) 
                 over (partition by account, grp order by date_) cnt
      from (
        select date_, account, amount, 
               date_ - sum(case when amount <= 0 then 1 else 0 end) 
                           over (partition by account order by date_) grp
          from t ))

demo

我假设日期是连续的,如果不是,那么请首先使用行编号。