SQL根据开始和结束时间对符合条件的时间序列进行分组

时间:2017-11-14 12:21:04

标签: sql vba ms-access access-vba

我正在分析电力系统时间序列数据,我试图找到满足某个布尔标志的连续数据点。

我想通过返回对应于拐点的开始和结束时间来查询该表,其中值从1变为0,0变为1。

如何实现下面的伪sql代码?

SELECT Time
FROM InputTable
WHERE InputTable.Value = 1
INTO OutputTable??, TimeStart??, TimeEnd??;

输入:

+-------+---------+------+
| Index |  Time   | Value|
+-------+---------+------+
|     0 | 00:00:01|   1  |
|     1 | 00:00:02|   1  |
|     2 | 00:00:03|   1  |
|     3 | 00:00:04|   0  |
|     4 | 00:00:05|   1  |
|     5 | 00:00:06|   1  |
|     6 | 00:00:07|   0  |
|     7 | 00:00:08|   1  |
+-------+---------+------+

输出:

+-------+-----------+----------+
| Index | TimeStart | TimeEnd  |
+-------+-----------+----------+
|     0 | 00:00:01  | 00:00:03 |
|     1 | 00:00:05  | 00:00:06 |
|     2 | 00:00:08  | 00:00:08 |
+-------+-----------+----------+

1 个答案:

答案 0 :(得分:1)

您需要根据相邻的“1”对值进行分组。这在MS Access中很棘手。可以在Access中使用的一种方法是在每行之前计算“0”(或非“1”值)的数量。

select ind, min(time), max(time)
from (select t.*,
             (select 1 + count(*)
              from inputtable as t2
              where t2.value = 0 and t2.time < t.time
             ) as ind
      from inputtable as t
     ) as t
where value = 1
group by ind