我们的数据库中有一个表,各种系统都会报告时间戳和值。该表称为数据表。 (我知道,我没有说出来。)
所以我的任务是完成并查找特定系统报告之间的时间差异。
我不知道怎么回事,我创建了一个临时表,例如:
CREATE TABLE #Readings(
id INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
timestamp DATETIME
)
然后我插入特定系统的所有读数:
INSERT INTO #Readings (timestamp)
SELECT ReadingAt
FROM data
WHERE SenId = 3
ORDER BY ReadingAt
最后,我运行了我的查询:
select r1.id, r1.timestamp, datediff(second, r1.timestamp, (select r2.timestamp
from #Readings r2 where r2.id = (r1.id - 1)))
from #Readings r1
where id > 1
但是这又回来了:
101 2011-07-14 04:44:05.443 <null>
102 2011-07-14 04:46:05.443 -120
103 2011-07-14 04:48:05.447 -120
104 2011-07-14 04:50:05.447 -120
105 2011-07-14 04:52:05.447 -120
106 2011-07-14 04:54:05.45 -120
107 2011-07-14 04:56:05.45 -120
108 2011-07-14 04:58:05.45 -120
109 2011-07-14 05:00:05.45 -120
110 2011-07-14 05:02:05.453 -120
所以我做了以下事情:
select r1.id, r1.timestamp, (select r2.timestamp from #Readings r2 where r2.id = (r1.id - 1))
from #Readings r1
where id > 1
返回了正确的日期。
所以,我想知道,我该怎么做?
感谢。
答案 0 :(得分:4)
让自己更简单,不要使用子查询!
select
r1.id,
r1.timestamp,
datediff(second, r2.timestamp, r1.timestamp) as TimeBetween
from
#Readings r1
left join #Readings r2 on
r1.id = r2.id+1
where
r1.id > 1
但是对于它的价值,第一个查询是正确的。您的datediff
函数是开始时间和结束时间之间的时间。因此,开始时间必须小于结束时间。这就是你得到否定的原因。
答案 1 :(得分:0)
以下是如何在一个查询中完成所有操作,没有任何临时表
SELECT T1.ReadingAt, T2.ReadingAt,
datediff(second, T2.ReadingAt, T1.ReadingAt) AS TimeBetween
FROM (SELECT ROW_NUMBER() OVER (ORDER BY ReadingAt) AS RowNumber, ReadingAt
FROM data
WHERE SenId = 3) t1
INNER JOIN
(SELECT ROW_NUMBER() OVER (ORDER BY ReadingAt) AS RowNumber, ReadingAt
FROM data
WHERE SenId = 3) t2 ON T1.RowNumber = T2.RowNumber + 1