Par*_*ker 9 sql postgresql time-series
我在表格中有传感器数据:
Time Value
10 100
20 200
36 330
46 440
Run Code Online (Sandbox Code Playgroud)
我想提取每个时间段的值的变化.理想情况下,我想得到:
Starttime Endtime Change
10 20 100
20 36 130
36 46 110
Run Code Online (Sandbox Code Playgroud)
我的SQL技能非常简陋,所以我倾向于将所有数据都输出到处理它的脚本然后将其推回到新表中,但我想我会问是否有一种灵活的方式来完成这一切在数据库中.
您可以使用 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)