如何查找某一列的日期和指定值的运行总计?

问题描述

以下是我的数据集的样子: [1]:https://i.stack.imgur.com/v6r9J.png

this-is-an-example-link

每次“状态”列的值从 IN 变为 OUT 时,我想计算天数列的运行总数。 2019 年 10 月 10 日,该值为 IN。 2019 年 10 月 11 日,该值为 OUT。所以运行总数应该是 1。

对于同一个客户,2019 年 4 月 23 日,值为 IN。 28 年 4 月 28 日,该值再次 OUT。所以运行总数应该是 5,因为它处于“IN”状态 5 天。

如何在 sql 中实现这个查询

解决方法

我会将此作为间隙和岛屿问题来解决。每次看到“IN”状态时都会启动一个岛:我们可以使用“IN”状态的窗口计数来识别这些“相邻”记录组,然后进行日期算术:

select t.*,date - min(date) over(partition by grp) as running_total_of_days
from (
    select t.*,sum(case when status = 'IN' then 1 else 0 end) 
            over(partition by custnumber order by date) as grp
    from mytable t
) t

计算日期差异的实际语法因数据库而异 - 您没有说明您使用的是哪个。以上适用于支持直接减去日期的数据库(如Oracle或Postgres);其他数据库具有相同的语法或功能。

这会将运行总数放在每一行上。如果您只想在每组的最后一个“OUT”行上使用它,则可以使用 case 表达式:

select t.*,case when status = 'OUT' and row_number() over(partition by grp order by date desc) = 1
        then date - min(date) over(partition by grp) 
    end as running_total_of_days
from (
    select t.*,sum(case when status = 'IN' then 1 else 0 end) 
            over(partition by custnumber order by date) as grp
    from mytable t
) t