包含过滤日期之间的记录

时间:2017-06-26 06:19:53

标签: sql tsql

我有一张表,其中有一组像这样的记录

  

TimeStart TimeEnd StoodType

     

2017-06-26 07:50:49.000 2017-06-26 11:33:13.000 95

     

2017-06-26 11:33:42.000 2017-06-26 11:35:07.000 90

     

2017-06-26 11:59:13.000 2017-06-26 12:16:33.000 94

     

2017-06-26 12:18:07.000 2017-06-26 12:21:38.000 94

     

2017-06-26 12:27:22.000 2017-06-26 12:29:51.000 94

     

2017-06-26 13:06:21.000 2017-06-26 13:08:19.000 90

我需要选择8:00和20:00之内的记录 喜欢

  

2017-06-26 07:50:49.000 2017-06-26 11:33:13.000 95

我尝试这个SQL

declare @StartTime datetime
declare @EndTime datetime

set @StartTime = '20170626 8:00'
set @EndTime = '20170626 20:00'

SELECT   TimeStart, TimeEnd, StoodType  FROM  dbo.WDT
    WHERE TimeStart BETWEEN  @StartTime AND @EndTime 

但它无济于事

有任何线索吗?

2 个答案:

答案 0 :(得分:1)

我找到了正确的解决方案。感谢 Stackoverflow

declare @StartTime datetime;
declare @EndTime datetime;

set @StartTime = '20170626 8:00';
set @EndTime = '20170626 20:00';       

SELECT (CASE   
      WHEN TimeStart < @StartTime THEN  @StartTime
     ELSE TimeStart
  END
  ) AS CorrectedTimeStart, (CASE   
      WHEN TimeEnd > @EndTime THEN  @EndTime
     ELSE TimeEnd
  END) AS CorrectedTimeEnd, 
  TimeStart, TimeEnd
     FROM
  (SELECT DISTINCT TimeStart, TimeEnd FROM WDT WHERE TimeStart BETWEEN  @StartTime AND @EndTime
  UNION
  SELECT DISTINCT TimeStart, TimeEnd FROM WDT WHERE TimeEnd BETWEEN  @StartTime AND @EndTime
  ) A

enter image description here

答案 1 :(得分:0)

当您更新信息时。看起来你想要所有开始,结束或完全重叠时间段的设置从早上8点到晚上8点。 如果你不需要与8 am / 8pm时间带完全重叠的行,只需删除最后两行。

set(handles.uitable1,'data',{});