查询/存储过程读取数据库记录并转换成其他形式?

时间:2018-07-31 19:56:28

标签: sql sql-server stored-procedures

我有服务,每5分钟将信息发送到服务器。我在数据库中有以下记录集:

RecordId | sensorId | status | timestamp
       1 |        3 |   good | 07/31/2018 2:10:00.000
       2 |        3 |   good | 07/31/2018 2:15:00.000
       3 |        3 |   good | 07/31/2018 2:20:00.000
       4 |        3 |   good | 07/31/2018 2:25:00.000
       5 |        3 |   good | 07/31/2018 2:30:00.000
       6 |        3 |    bad | 07/31/2018 2:35:00.000
       7 |        3 |    bad | 07/31/2018 2:40:00.000
       8 |        3 |   good | 07/31/2018 2:45:00.000
       9 |        3 |    bad | 07/31/2018 2:50:00.000

现在,我需要编写一个查询/存储过程,以读取上述记录并将以下格式的数据加载到另一个表中

 id | sensorId | status | From                   | To
101 |         3|   good | 07/31/2018 2:10:00.000 | 07/31/2018 2:30:00.000
102 |         3|    bad | 07/31/2018 2:35:00.000 | 07/31/2018 2:40:00.000
103 |         3|   good | 07/31/2018 2:45:00.000 | 07/31/2018 2:50:00.000
104 |         3|    bad | 07/31/2018 2:50:00.000 | 07/31/2018 2:55:00.000

我们可以将数据从给定表转换为上面的表吗?请提出转换数据的方法/解决方案?

1 个答案:

答案 0 :(得分:0)

这称为“缺口和孤岛”问题。一个相对简单的解决方案是使用row_numbers()的差异来识别相似状态的“岛屿”。

select sensorid, status, min(timestamp), max(timestamp)
from (select t.*,
             row_number() over (partition by sensorid order by timestamp) as seqnum_s,
             row_number() over (partition by sensorid, status order by timestamp) as seqnum_ss
      from t
     ) t
group by sensorid, status, (seqnum_s - seqnum_ss);