Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 将表的两行之间的绝对时间差放入另一个表中_Sql Server_Datetime - Fatal编程技术网

Sql server 将表的两行之间的绝对时间差放入另一个表中

Sql server 将表的两行之间的绝对时间差放入另一个表中,sql-server,datetime,Sql Server,Datetime,我有一个带有时间戳的表和一个布尔值,表示存在一个类似这样的东西 id timeStamp thingIsIn 1 t1 1 4 t2 0 5 t3 1 7 t4 0 id时间戳thingsin 1 t1 1 4 t20 5 t3 1 7 t4 0 其中t1-t4只是填充表时来自getdate()函数的日期时间值。由于重复项被删除,我可能有非连续的id。

我有一个带有时间戳的表和一个布尔值,表示存在一个类似这样的东西

id timeStamp thingIsIn 1 t1 1 4 t2 0 5 t3 1 7 t4 0 id时间戳thingsin 1 t1 1 4 t20 5 t3 1 7 t4 0 其中t1-t4只是填充表时来自getdate()函数的日期时间值。由于重复项被删除,我可能有非连续的id。我需要把上班时间和下班时间分别送到一张桌子上。inTimes表的一个示例:

timeStamp duration t1 t2-t1 (this is the timeStamp of when it went in and how long it was there) t3 t4-t3 时间戳持续时间 t1 t2-t1(这是它进入的时间戳以及在那里的时间) t3 t4-t3 其中t2-t1可以是任意长度,所以我想要datetime中的时间,而不是datetime的一部分


如何计算时差以及如何将其发送到新表?

基本上需要使用窗口函数来获取下一条记录的值。下面的查询应该可以工作

create table time_stamp
(
  id int,
  timeStamp DateTime,
  thingIsIn int
);

insert into time_stamp VALUES(1, getdate(), 1);
insert into time_stamp VALUES(7, getdate() + 4, 1);
insert into time_stamp VALUES(4, getdate() + 1, 0);
insert into time_stamp VALUES(5, getdate() + 2, 1);
insert into time_stamp VALUES(6, getdate() + 5, 0);
insert into time_stamp VALUES(8, getdate() + 3, 0);

SELECT t.timeStamp, DATEDIFF(hour, t.timestamp, lead_time) hour_difference
FROM (SELECT ts.id, ts.timeStamp, ts.thingIsIn, LEAD(timeStamp) OVER (ORDER BY timeStamp) lead_time
      FROM time_stamp ts) t
WHERE t.thingisin = 1

SQL Server有
DATEDIFF
函数来计算时间间隔长度DATEDIFF(datepart、startdate、enddate)我不能使用datepart,我需要以YYYYMMDDHmmss.000
mm
为单位的总时差,这对时间间隔没有多大意义——是28天、29天、30天还是31天?对于
yyyy
——闰年与否类似?是否有某种方法可以执行t2-t1而不限于一种时间度量,即秒或天?如果我的东西是在65天,报告天是有帮助的,但我失去了准确性或小时和分钟等,但如果我的东西只是在几秒钟,那么数据是完全无用的。我是否必须分别获取每个时间度量值,然后在一个艰难的过程中以某种方式连接它?datetime数据类型不是时间度量值。如果您收到2020-01-01和2020-01-02作为日期值,您会期望什么?对我来说,这听起来像是一场灾难。