如何将表中不同记录的数据映射到SQL中的单个记录?

问题描述

我是 sql 的新手。以下是我正在处理的数据类型:

样本输入:

Description                                       Timestamp
-----------                                       ---------
The *machine1- is being analysed                  (time)
The *wheel- is working properly                   (time)
The *motor- requires maintenance                  (time)
The *machine2- is being analysed                  (time)
The *handle- is working properly                  (time)
The *wheel- requires maintenance                  (time)
.
.
.

表 Machines 按记录的时间戳顺序排列。按此顺序排列时,记录遵循以下模式:

"..... 正在分析" ==> ".... 正常工作" ==> ".... 需要维护"

所以,逻辑可以是这样的:一旦你遇到“....需要维护”事件,从这个事件和前两个事件中提取数据并将它们显示一个记录中。

或者,一旦您遇到“..... 正在分析”事件,从该事件和接下来的两个事件中提取数据并将它们显示在单个记录中。

我需要遍历以上数千个事件,检查描述类型,并提取表格中的相关信息。

所需的输出

Machine        Working Part        damaged Part
-------        ------------        ------------
machine1       wheel               motor
machine2       handle              wheel
.
.
.

我写的查询

select 
case when Description like '%analysed%' then SUBSTRING(Description,POSITION('*' IN Description)+1,POSITION('-' IN Description) - POSITION('*' IN Description)-1) end as Machine,case when Description like '%working properly%' then SUBSTRING(Description,POSITION('-' IN Description) - POSITION('*' IN Description)-1) end as Working Part,case when Description like '%maintenance%' then SUBSTRING(Description,POSITION('-' IN Description) - POSITION('*' IN Description)-1) end as damaged Part
from Machines
order by Timestamp asc

但我的输出是这样的:

Machine        Working Part        damaged Part
-------        ------------        ------------
machine1       
               wheel
                                   motor
machine2       
               handle
                                   wheel
.
.
.

我正在使用 Vertica,我在网上看到它不擅长处理循环和变量。有人可以告诉我如何将这些数据从一组 3 个语句映射到所需输出中提到的单个记录中,并将它们显示表格

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)