sql查询找到正确的引擎对运行

waxmsbnn  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(350)

我在一个现有的表中获得了数据,其中包含活动(a)和非活动(i)等事件。如果组件处于活动或非活动状态,则类似于日志记录。由于旧接口,没有正确的组件对。
hier是一个简短的示例数据库

"id" "component_number" "timestamp" "status"
"1" "1" "2020-05-10 16:30:00" "A"
"2" "1" "2020-05-18 16:34:05" "A"
"3" "1" "2020-05-19 16:36:01" "I"
"4" "1" "2020-05-19 16:36:52" "A"
"5" "1" "2020-05-19 16:38:57" "I"
"6" "2" "2020-05-11 17:04:50" "A"
"7" "2" "2020-05-15 10:00:00" "A"
"8" "2" "2020-05-16 11:25:16" "I"

例如,1号发动机在2020-05-10 16:30:00启动(激活),并在2020-05-19 16:36:01停止(非激活)。但是我在2020-05-18 16:34:05有一个活动的附加条目。
当发动机运转时,我必须找到正确的对。例如:2020-05-10 16:30:00和2020-05-19 16:36:01。这个列表不仅包括一个引擎,还可以有更多的引擎。
我正在寻找一个查询字符串来获取正确的对(结果1),或者一个字符串来获取所需的事件(结果2)。我不知道什么更容易?
结果1:

"component_number" "start" "end"
"1" "2020-05-10 16:30:00" "2020-05-19 16:36:01"
"1" "2020-05-19 16:36:52" "2020-05-19 16:38:57"
"2" "2020-05-11 17:04:50" "2020-05-16 11:25:16"

结果2:

"id" "component_number" "timestamp" "status"
"1" "1" "2020-05-10 16:30:00" "A"
"3" "1" "2020-05-19 16:36:01" "I"
"4" "1" "2020-05-19 16:36:52" "A"
"5" "1" "2020-05-19 16:38:57" "I"
"6" "2" "2020-05-11 17:04:50" "A"
"8" "2" "2020-05-16 11:25:16" "I"

我尝试了子查询和join,但没有成功。有人有什么主意或提示怎么处理吗?

9fkzdhlc

9fkzdhlc1#

这是一个缺口和孤岛问题。我建议你 lag() 还有一扇Windows sum() 定义组。基本上,每个月都会有一个新的团队开始 'A' 前面有一个 'I' .
这将提供第一个结果集:

select 
    component_number, 
    min(timestamp) start_timestamp,
    max(timestamp) end_timestamp
from (
    select 
        t.*, 
        sum(case when status = 'A' and lag_status = 'I' then 1 else 0 end) 
            over(partition by component_number order by timestamp) grp
    from (
        select 
            t.*,
            lag(status) 
                over(partition by component_number order by timestamp) lag_status
        from mytable t
    ) t
) t
group by component_number, grp

第二个结果集需要较少的嵌套:

select id, component_number, timestamp, status
from (
    select 
        t.*,
        lag(status) 
            over(partition by component_number order by timestamp) lag_status
    from mytable t
) t
where status = 'I' or lag_status is null or lag_status = 'I'

db小提琴演示(mariadb 10.3):

component_number | start_timestamp     | end_timestamp      
---------------: | :------------------ | :------------------
               1 | 2020-05-10 16:30:00 | 2020-05-19 16:36:01
               1 | 2020-05-19 16:36:52 | 2020-05-19 16:38:57
               2 | 2020-05-11 17:04:50 | 2020-05-16 11:25:16
id | component_number | timestamp           | status
-: | ---------------: | :------------------ | :-----
 1 |                1 | 2020-05-10 16:30:00 | A     
 3 |                1 | 2020-05-19 16:36:01 | I     
 4 |                1 | 2020-05-19 16:36:52 | A     
 5 |                1 | 2020-05-19 16:38:57 | I     
 6 |                2 | 2020-05-11 17:04:50 | A     
 8 |                2 | 2020-05-16 11:25:16 | I

相关问题