SQL Server 不支持 SQL 标准间隔数据类型。最好的办法是以秒为单位计算差异,并使用函数来格式化结果。本机函数 CONVERT() 可能看起来工作正常只要您的间隔时间少于 24 小时。但 CONVERT() 并不是一个好的解决方案。
create table test (
id integer not null,
ts datetime not null
);
insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');
值的选择方式是:
- id = 1,经过时间为1小时
- id = 2,经过的时间是 2 小时,并且
- id = 3,经过的时间是3小时。
此 SELECT 语句包括一列用于计算秒数,另一列使用 CONVERT() 进行减法。
select t.id,
min(ts) start_time,
max(ts) end_time,
datediff(second, min(ts),max(ts)) elapsed_sec,
convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;
ID START_TIME END_TIME ELAPSED_SEC DO_NOT_USE
1 January, 01 2012 08:00:00 January, 01 2012 09:00:00 3600 01:00:00
2 January, 01 2012 08:30:00 January, 01 2012 10:30:00 7200 02:00:00
3 January, 01 2012 09:00:00 January, 02 2012 12:00:00 97200 03:00:00
请注意 ID 号 3 上的 27 小时差异的误导性“03:00:00”。
SQL Server 中格式化经过时间的函数 https://stackoverflow.com/a/11191244/562459