获取状态更改的最小值和最大值

时间:2018-08-28 16:55:37

标签: sql sql-server

我有一张表格,每秒记录一次状态。我需要掌握每次更改的状态更改的开始和停止,以及更改次数的计数。状态在一天中不断在表格中重复(状态0到状态5)。

所以我的输出将是:

1, 2018-08-28 5:20:35, 2018-08-28 5:20:36
0, 2018-08-28 5:21:05, 2018-08-28 5:21:36
4, 2018-08-28 5:22:05, 2018-08-28 5:23:06
0, 2018-08-28 5:23:35, 2018-08-28 5:23:35 
1, 2018-08-28 5:23:36, 2018-08-28 5:24:05



t_stamp,             status
2018-08-28 5:20:35,     1
2018-08-28 5:20:36,     1
2018-08-28 5:21:05,     0
2018-08-28 5:21:06,     0
2018-08-28 5:21:35,     0
2018-08-28 5:21:36,     0
2018-08-28 5:22:05,     4
2018-08-28 5:22:06,     4
2018-08-28 5:22:35,     4
2018-08-28 5:22:36,     4
2018-08-28 5:23:05,     4
2018-08-28 5:23:06,     4
2018-08-28 5:23:35,     0
2018-08-28 5:23:36,     1
2018-08-28 5:24:05,     1

Select Status ,
       MIN(t_stamp) 'Min_Time',
       Max(t_stamp) 'Max_time'  
From test_table  
group by Status, t_stamp

1 个答案:

答案 0 :(得分:1)

您需要row_numbers的区别:

SELECT status, MIN(t_stamp), MAX(t_stamp)
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY t_stamp) AS seq1,
                ROW_NUMBER() OVER (PARTITION BY status ORDER BY t_stamp) AS seq2
      FROM table t
     ) t
GROUP BY status, (seq1- seq2);