在 ORACLE 中查找帐户的活跃天数

Find number of days Active days for account in ORACLE

我正在尝试查找关闭特定帐户的天数。

我有 table 如下所示:

OPER_DAY    |   CODE_FILIAL  |  SUM_IN         |      SALDO_OUT     |   ACC   
-------------------------------------------------------------------------------
2020-11-02  |   00690        |   0             |   1578509367.58    | 001
2020-11-03  |   00690        |   1578509367.58 |   9116497.5        | 001
2020-11-04  |   00690        |   9116497.5     |   0                | 001
2020-11-02  |   00690        |   0             |   157430882.96     | 101
2020-11-03  |   00690        |   157430882.96  |   0                | 101
2020-11-09  |   00690        |   0             |   500000           | 101
2020-11-19  |   00690        |   500000        |   0                | 101


对于特定的 ACC,一天以 0 总和结束,以 0 结束。我需要找出孝子结帐的天数。 例如,对于 ACC 001,从 2020-11-02 到 2020-11-04 花了 2 天。 101 ACC 花了 11 天。因为从 2020-11-02 - 2020-11-03 -> 1 天, 从 2020-11-09 - 2020-11-19 -> 10 天 总体 13 天.

我想要的结果:

----------------------------
CODE_FILIAL   | NUM_OF_DAYS
---------------------------
  00690       |  13

这看起来像是一个缺口和孤岛问题。岛屿以 sum_in 中的值 0 开始,并以 saldo_out 中的 0 值结束。

假设每次开始总是最多有一个结束,您可以使用 window 函数和聚合,如下所示:

select code_filial, sum(end_dt - start_dt) as num_of_days
from (
    select code_filial, acc, grp
        min(oper_day) as start_dt,
        max(case when saldo_out = 0 then oper_day end) as end_dt
    from (
        select t.*,
            sum(case when sum_in = 0 then 1 else 0 end) over(partition by code_filial, acc order by oper_day) as grp
        from mytable t
    ) t
    group by code_filial, acc, grp
) group by code_filial

这是通过构建具有 window 总和的记录组来实现的,每当给定的 (code_filial, acc) 元组在列 sum_in 中遇到 0 的值时,总和就会递增.然后我们可以使用聚合来计算相应的结束日期。最后一步是按 code_filial.

聚合