我在表格中有传感器数据:
Time Value
10 100
20 200
36 330
46 440
我想提取每个时间段的值变化。理想情况下,我想得到:
Starttime Endtime Change
10 20 100
20 36 130
36 46 110
我的SQL技能非常简陋,所以我倾向于将所有数据输出到处理它的脚本,然后将其推回到新表中,但我想我会问是否有一个光滑的方式在数据库中完成所有操作。
答案 0 :(得分:3)
Select a.Time as StartTime, b.time as EndTime, b.time-a.time as TimeChange, b.value-a.value as ValueChange
FROM YourTable a, YourTable b
WHERE b.time = (Select MIN(c.time) FROM YourTable c WHERE c.time>a.time)
答案 1 :(得分:2)
Select a.Time as StartTime
, b.time as EndTime
, b.time-a.time as TimeChange
, b.value-a.value as ValueChange
FROM YourTable a
Left outer Join YourTable b ON b.time>a.time
Left outer Join YourTable c ON c.time<b.time AND c.time > a.time
Where c.time is null
Order By a.time
答案 2 :(得分:1)
您可以使用SQL窗口函数,以下是基于BIGQUERY语法的示例。
SELECT
LAG(time, 1) OVER (BY time) AS start_time,
time AS end_time,
(value - LAG(value, 1) OVER (BY time))/value AS Change
from data
答案 3 :(得分:0)
首先,我会在表格中添加一个id列,以便您可以预测某些行从一行到另一行。
然后,我会尝试以下查询:
SELECT t1.Time AS 'Starttime', t2.Time AS 'Endtime',
(t2.Value - t1.Value) AS 'Change'
FROM SensorData t1
INNER JOIN SensorData t2 ON (t2.id - 1) = t1.id
ORDER BY t1.Time ASC
我打算创建一个测试表来为自己尝试这个,所以我不知道它是否有效但是值得一试!
<强>更新强> 修复了一个小问题(CHANGE是一个受保护的单词,必须引用)但测试它,它的工作原理!它完全产生上面定义的结果。
答案 4 :(得分:0)
这有用吗?
WITH T AS
(
SELECT [Time]
, Value
, RN1 = ROW_NUMBER() OVER (ORDER BY [Time])
, RN2 = ROW_NUMBER() OVER (ORDER BY [Time]) - 1
FROM SensorData
)
SELECT
StartTime = ISNULL(t1.[time], t2.[time])
, EndTime = ISNULL(t2.[time], 0)
, Change = t2.value - t1.value
FROM T t1
LEFT OUTER JOIN
T t2
ON t1.RN1 = t2.RN2