如何显示包含超过2天的记录的结果

时间:2018-01-11 14:10:02

标签: sql-server sql-date-functions

我有一个我需要查询的数据库,这个数据库跨越了早上的夜晚,即。晚上10点 - 早上6点。

问题是如果我运行以下查询

 select * from F305BatchLog 
where  StartDate between '2018-01-10' And '2018-01-11' 
and StartTime between '22:00:00' And '06:00:00'
order by TimeStamp asc

它没有给我任何结果。我基本上需要从特定日期开始运行查询,如果它重叠到第二天早上直到早上6点将包含这些结果

我想要的结果应该是

PC4424 SMR                                          F305    1   2018-01-10  Totalised   118.9988174 2018-01-10 23:15:57.000
PC4424 SMR                                          F305    2   2018-01-10  Totalised   119.4488068 2018-01-10 23:23:41.000
PC4424 SMR                                          F305    3   2018-01-10  Totalised   120.8987885 2018-01-10 23:30:50.000
PC4424 SMR                                          F305    4   2018-01-10  Totalised   121.2987823 2018-01-10 23:37:01.000
PC4424 SMR                                          F305    5   2018-01-10  Totalised   120.8487854 2018-01-10 23:44:33.000
PC4424 SMR                                          F305    6   2018-01-10  Totalised   120.7487946 2018-01-10 23:54:09.000
PC4424 SMR                                          F305    7   2018-01-11  Totalised   121.0987854 2018-01-11 00:01:24.000
PC4424 SMR                                          F305    8   2018-01-11  Totalised   119.5988083 2018-01-11 00:09:41.000
PC4424 SMR                                          F305    9   2018-01-11  Totalised   119.5488129 2018-01-11 00:17:22.000
PC4424 SMR                                          F305    10  2018-01-11  Totalised   120.1488037 2018-01-11 00:24:30.000
PC4424 SMR                                          F305    11  2018-01-11  Totalised   120.598793  2018-01-11 00:31:00.000
PC4424 SMR                                          F305    12  2018-01-11  Totalised   120.1488037 2018-01-11 00:37:54.000
PC4424 SMR                                          F305    13  2018-01-11  Totalised   121.1487885 2018-01-11 00:44:13.000
PC4424 SMR                                          F305    14  2018-01-11  Totalised   121.0987854 2018-01-11 00:50:45.000
PC4424 SMR                                          F305    15  2018-01-11  Totalised   120.4987946 2018-01-11 00:57:37.000
PC4424 SMR                                          F305    16  2018-01-11  Totalised   119.6488037 2018-01-11 01:04:26.000

1 个答案:

答案 0 :(得分:0)

分别测试晚上和早晨:

select * from F305BatchLog 
where  (StartDate between '2018-01-10' And '2018-01-11' 
        and StartTime between '22:00:00' And '23:59:59.9999')
   or  (StartDate between '2018-01-11' and '2018-01-12'
        and StartTime between '00:00:00' and '06:00:00')
order by TimeStamp asc

更好的是,假设TimeStamp是DateTime列:

select * from F305BatchLog
where TimeStamp between '2018-01-10 22:00:00' and '2018-01-11 06:00:00'
order by TimeStamp asc

所做的是使用DATEADD或其他功能将StartDate和StartTime组合成一个日期时间变量。这将导致您的查询非SARGable并破坏使用任何索引来优化它的机会。