这是我的表格数据:
ID FromDate ToDate
1 2018-12-07 12:25:47.000 2018-12-07 18:28:44.150
2 2018-12-07 18:28:44.150 2018-12-07 22:33:11.867
3 2018-12-07 22:33:11.867 2018-12-08 03:14:16.630
4 2018-12-08 03:14:16.630 2018-12-09 02:10:44.723
这是我获取时差的查询
Select DATEDIFF(HH,FromDate,TODate) As Hour,* from Test Where FromDate Between '2018-12-07 12:25:47.000' And '2018-12-08 12:25:47.000'
or ToDate Between '2018-12-07 12:25:47.000' And '2018-12-08 12:25:47.000'
Select DATEDIFF(HH,FromDate,TODate) As Hour,* from Test Where FromDate Between '2018-12-08 12:25:47.000' And '2018-12-09 12:25:47.000'
or ToDate Between '2018-12-08 12:25:47.000' And '2018-12-09 12:25:47.000'
我的第一个查询的输出应该是
6
4
5
9
对于第二个查询,输出应为
14
原因:我的第四个数据都在两个查询输出下,但是我只需要在选择查询中传递的日期范围之间的时差即可。
答案 0 :(得分:1)
这应该使您入门:
declare @table table (id int ,fromdate datetime,todate datetime)
insert into @table
values
(1 ,'2018-12-07 12:25:47.000','2018-12-07 18:28:44.150'),
(2 ,'2018-12-07 18:28:44.150','2018-12-07 22:33:11.867'),
(3 ,'2018-12-07 22:33:11.867','2018-12-08 03:14:16.630'),
(4 ,'2018-12-08 03:14:16.630','2018-12-09 02:10:44.723')
declare @todate datetime = '2018-12-08 12:25:47.000'
declare @fromdate datetime = '2018-12-08 12:25:47.000'
Select case when @todate > todate then DATEDIFF(HH,FromDate,TODate) else
datediff(HH,fromdate,@todate) end As Hour,* from @table Where
( FromDate Between '2018-12-07 12:25:47.000' And '2018-12-08 12:25:47.000'
or ToDate Between '2018-12-07 12:25:47.000' And '2018-12-08 12:25:47.000')
Select case when @fromdate > fromdate then DATEDIFF(HH,@fromdate,TODate) else datediff(HH,fromdate,todate) end As Hour,* from @table Where FromDate Between '2018-12-08 12:25:47.000' And '2018-12-09 12:25:47.000'
or ToDate Between '2018-12-08 12:25:47.000' And '2018-12-09 12:25:47.000'