根据最近的日期向crieteria显示结果

时间:2016-05-02 09:36:33

标签: sql closest

开启/关闭日期时间

1   2016-05-02 06:04:08.000
0   2016-05-02 06:08:42.000
1   2016-05-02 06:11:54.000
1   2016-05-02 06:13:41.000
1   2016-05-02 06:14:07.000
1   2016-05-02 06:14:28.000
1   2016-05-02 06:14:50.000
1   2016-05-02 06:15:59.000
1   2016-05-02 06:16:26.000
1   2016-05-02 06:24:23.000
0   2016-05-02 07:46:32.000
1   2016-05-02 10:14:06.000

我在整理方面遇到了问题。

我想用开/关显示日期时间。 但我只希望最接近/关闭= 1之前 开/关= 0.

期望的结果:

on/off  datetime
1   2016-05-02 06:04:08.000
0   2016-05-02 06:08:42.000
1   2016-05-02 06:24:23.000
0   2016-05-02 07:46:32.000
1   2016-05-02 10:14:06.000

额外:如果最后没有0,则应该给出getdate()

下一步

非常感谢 发现我需要做的下一步

开始结束 2016-05-02 06:04:14.000 NULL NULL 2016-05-02 06:08:31.000 2016-05-02 06:27:27.000 NULL NULL 2016-05-02 06:46:39.000 2016-05-02 06:47:10.000 NULL NULL 2016-05-02 06:51:31.000 2016-05-02 06:54:30.000 NULL NULL 2016-05-02 07:08:51.000 2016-05-02 07:10:21.000 NULL NULL 2016-05-02 07:12:31.000 2016-05-02 07:18:32.000 NULL NULL 2016-05-02 07:28:13.000 2016-05-02 07:29:02.000 NULL NULL 2016-05-02 07:33:00.000 2016-05-02 07:44:35.000 NULL NULL 2016-05-02 07:45:47.000

我知道如果我有一个参考,我会用一个组做这个,但现在我只有0和1

期望的结果

开始结束 2016-05-02 06:04:14.000 2016-05-02 06:08:31.000 2016-05-02 06:27:27.000 2016-05-02 06:46:39.000 2016-05-02 06:47:10.000 2016-05-02 06:51:31000 2016-05-02 06:54:30.000 2016-05-02 07:08:51.000 2016-05-02 07:10:21.000 2016-05-02 07:12:31.000 2016-05-02 07:18:32.000 2016-05-02 07:28:13.000 2016-05-02 07:29:02.000 2016-05-02 07:33:00.000 2016-05-02 07:44:35.000 2016-05-02 07:45:47.000

1 个答案:

答案 0 :(得分:1)

select ThisRow.*
from
( SELECT row_number() over (order by Date_Time) as RowNr
      ,[OnOff]
      ,[Date_Time]  FROM [VH_Stam].[dbo].[Values]
   )  ThisRow 
  left outer join
  ( SELECT row_number() over (order by Date_Time) as RowNr
      ,[OnOff]
      ,[Date_Time] FROM [VH_Stam].[dbo].[Values]
   )  PreviousRow on
  ThisRow.RowNr = PreviousRow.RowNr +1
Where ThisRow.RowNr = 1 or
PreviousRow.OnOff <> ThisRow.OnOff

始终选择行号1,因为它总是与不存在的行号0不同。否则只选择与前一行不同的行。