【问题标题】:SQL to group time series meeting a criteria, according to start and end timeSQL根据开始和结束时间对满足条件的时间序列进行分组
【发布时间】:2017-11-14 12:21:03
【问题描述】:

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

我想通过返回对应于拐点的开始和结束时间来查询这个表,其中值从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 |
+-------+-----------+----------+

【问题讨论】:

    标签: sql ms-access vba


    【解决方案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
    

    【讨论】:

    • 感谢您给我这个想法,现在我通过分析您的示例代码的工作原理,终于了解了 group by 和 sub-queries 背后的直觉。 (刚刚看了你的书,好评!肯定会得到一本。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多