SQL - 如何计算两个值之间的行数?

SQL - How to count rows between two values?

我有一个 SQL table,其中包含时间戳和关联值。看起来像这样:

ORIGINAL_TABLE:

timestamp value
2022-06-03 00:09:15.000 75
2022-06-03 00:09:16.000 0
2022-06-03 00:09:19.000 0
2022-06-03 00:09:29.000 12
2022-06-03 00:09:44.000 0
2022-06-03 00:09:55.000 5

我正在尝试制作一个像这样的 table,它只包含 timestamp_start 字段中 value==0 的行。在timestamp_end字段中,包含下一个不等于0的值的时间戳:

WANTED_TABLE :

timestamp_start timestamp_end
2022-06-03 00:09:16.000 2022-06-03 00:09:29.000
2022-06-03 00:09:44.000 2022-06-03 00:09:55.000

我试过使用

coalesce(lead(timeStamp,SELECT COUNT(*) 
FROM ORIGINAL_TABLE
WHERE value=0

但是它只计算值 == 0 的行数

有什么建议吗?谢谢!

不知道你用的是什么数据库。但是我在 PostgreSQL 中写了这个 SQL 查询,我认为这个查询在许多数据库中都是 运行。

with org_table as materialized 
(
    select
        row_number() over (order by "timestamp") as r_num,
        "timestamp", 
        "value" 
    from original_table 
)
select min(a1.begintime) as begintime, a1.endtime from (
    select  
        t1."timestamp" as begintime, 
        min(t2."timestamp") as endtime
    from org_table t1 
    inner join org_table t2 on t2.r_num > t1.r_num and t2.value > 0
    where t1.value = 0 
    group by t1."timestamp"
) a1 
group by a1.endtime

结果:

begintime                   endtime
2022-06-03 00:09:16.000     2022-06-03 00:09:29.000
2022-06-03 00:09:44.000     2022-06-03 00:09:55.000