我有2列数据类型为Time。
实施例
08:00:00 - 12:00:00 = 4
08:30:00 - 23:00:00 = 15.5
20:00:00 - 00:00:00 = 4
22:00:00 - 06:00:00 = 8
答案 0 :(得分:3)
所有建议使用ABS
的答案似乎都在误解这里的情况。如果结果为负,则表示时间越过了日期边界,并且简单的补救措施是在结果中添加24小时以获得正确的值。
由于你只有时间,我们必须假设任何给定的一对代表一段不到24小时的时间(否则,没有办法区分代表2小时间隔的一对时间)一对代表26小时间隔的次数。)
因此,我们可以做的是始终将24小时添加到结果中,然后将结果模数为24小时。
以分钟计算:
SELECT (DATEDIFF(minute,FirstValue,SecondValue) + (24*60)) % (24*60)
答案 1 :(得分:1)
使用declare @t1 as time = '08:30:00';
declare @t2 as time = '23:00:00';
select abs(cast((datediff(minute, @t1, @t2)) as float) / 60);
<强>查询强>
14.5
<强>结果强>
@t1
您可以将变量@t2
和CASE
更改为列名。
<强>更新强>
您可以使用select
case when t1 > t2 then
cast(
datediff(
minute,
cast(
cast(
getdate() as date
)
as varchar(50)
)
+ ' ' +
cast(
cast(
left(t1, charindex('.', t1, 1) - 1)
as varchar(50)
)
as datetime
),
cast(
cast(
getdate() + 1 as date
)
as varchar(50)
)
+ ' ' +
cast(
cast(
left(t2, charindex('.', t1, 1) - 1)
as varchar(50)
)
as datetime
)
)
as float
) / 60
else cast((datediff(minute, t1, t2)) as float) / 60 end
from [your_table_name];
表达式来检查第一次比第二次列值更大的时间。如果它更大,那么第二个时间列应该在第二天。
<强>查询强>
{{$foo_srv := service "foo"}}
{{if $foo_srv}}
{{$last := len $foo_srv | subtract 1}}
servers=
{{- range $i := loop $last}}
{{- with index $foo_srv $i}}{{.Address}}{{.Port}},{{end}}
{{- end}}
{{- with index $foo_srv last}}{{.Address}}{{.Port}}{{end}}/bogus
{{end}}
答案 2 :(得分:1)
DECLARE @start time;
DECLARE @end time;
DECLARE @null time;
SET @start = '09:06:00';
SET @end = '21:27:00';
SET @null = '00:00:00';
SELECT DATEADD(SECOND, - DATEDIFF(SECOND, @end, @start), @null)
答案 3 :(得分:1)
DECLARE @time1 TIME ='22:00:00'
DECLARE @time2 TIME ='06:00:00'
SELECT CEILING(CAST(Diff as decimal)/(60 * 60)) FROM (SELECT
CASE WHEN CAST(DATEDIFF(SECOND,@time1,@time2) AS INT) > 0 THEN CAST(DATEDIFF(SECOND,@time1,@time2) AS INT)
ELSE (ABS(CAST(DATEDIFF(SECOND,CAST('23:59:59' AS TIME),@time1) AS INT)) + ABS(CAST(DATEDIFF(SECOND,@time2,CAST('00:00:00' as TIME)) AS INT)))
END AS Diff) AS A
<强>更新强>
上面的结果使用天花板功能将结果舍入到下一个小时,在片段下方使用小数部分
DECLARE @time1 TIME ='023:30:00'
DECLARE @time2 TIME ='06:00:00'
SELECT Round(CAST(Diff as decimal)/(60 * 60),2) FROM (SELECT
CASE WHEN CAST(DATEDIFF(SECOND,@time1,@time2) AS INT) > 0 THEN CAST(DATEDIFF(SECOND,@time1,@time2) AS INT)
ELSE (ABS(CAST(DATEDIFF(SECOND,CAST('23:59:59' AS TIME),@time1) AS INT)) + ABS(CAST(DATEDIFF(SECOND,@time2,CAST('00:00:00' as TIME)) AS INT)))
END AS Diff) AS A
答案 4 :(得分:0)
使用DATEDIFF功能
作为下一个
select datediff(hour,'08:00:00','12:00:00')
结果: -
4
<强>更新强>
获取绝对值(正值)使用ABS函数作为下一个
select abs(datediff(hour,'22:00:00','06:00:00'))
结果: -
16
<强> UPDATE2: - 强>
declare
@StartTime datetime = '22:00:00',
@EndTime datetime = '06:00:00'
if (datepart(hour,@StartTime) >= 12)
set @StartTime = dateadd(day,-1,@StartTime)
select abs(datediff(hour,@StartTime,@EndTime))
结果: -
8