SQL Server许多不规则测量值之间的差异
我有一个SQL server数据库,表中包含100个测量点的测量数据。每一个都以大约5秒的间隔进行测量。其格式如下:SQL Server许多不规则测量值之间的差异,sql,sql-server,tsql,sql-server-2012,Sql,Sql Server,Tsql,Sql Server 2012,我有一个SQL server数据库,表中包含100个测量点的测量数据。每一个都以大约5秒的间隔进行测量。其格式如下: MeasurementPointID timestamp value 001234 03-01-2015 00:02:03 100 001234 03-01-2015 00:02:08 120 001234
MeasurementPointID timestamp value
001234 03-01-2015 00:02:03 100
001234 03-01-2015 00:02:08 120
001234 03-01-2015 00:02:13 130
001234 03-01-2015 00:02:19 160
001234 03-01-2015 00:02:22 200
001236 03-01-2015 00:02:04 400
001236 03-01-2015 00:02:09 405
001236 03-01-2015 00:02:14 420
001236 03-01-2015 00:02:19 445
001236 03-01-2015 00:02:25 470
Etc.
我想知道如何使用自前一个时间戳以来测量值的变化除以时间段(自前一个时间戳)来创建视图
MeasurementPointID时间戳changeDivPeriod
001234 03-01-2015 00:02:03 0您可以使用窗口函数和自连接(如果需要,请使用视图包装):
输出:
╔════════════════════╦═════════════════════╦═════════════════╗
║ MeasurementPointID ║ timestamp ║ changeDivPeriod ║
╠════════════════════╬═════════════════════╬═════════════════╣
║ 001234 ║ 2015-03-01 00:02:03 ║ 0 ║
║ 001234 ║ 2015-03-01 00:02:08 ║ 4 ║
║ 001234 ║ 2015-03-01 00:02:13 ║ 2 ║
║ 001234 ║ 2015-03-01 00:02:19 ║ 5 ║
║ 001234 ║ 2015-03-01 00:02:22 ║ 13.333333333333 ║
║ 001236 ║ 2015-03-01 00:02:04 ║ 0 ║
║ 001236 ║ 2015-03-01 00:02:09 ║ 1 ║
║ 001236 ║ 2015-03-01 00:02:14 ║ 3 ║
║ 001236 ║ 2015-03-01 00:02:19 ║ 5 ║
║ 001236 ║ 2015-03-01 00:02:25 ║ 4.166666666666 ║
╚════════════════════╩═════════════════════╩═════════════════╝
使用SQL Server 2012+
,您可以利用超前/滞后
:
SELECT
MeasurementPointID,
[timestamp],
[changeDivPeriod] = COALESCE(1.0 * ([value] - LAG ([value]) OVER ( PARTITION BY MeasurementPointID ORDER BY [timestamp] ))
/ NULLIF(DATEDIFF(second, LAG ([timestamp]) OVER ( PARTITION BY MeasurementPointID ORDER BY [timestamp]), [timestamp]),0),0)
FROM #tab
40/3是13.333333,而不是10。行(160和200)和3秒差异IP:使用适当的软件(MySQL、Oracle、DB2等)和版本标记数据库问题很有帮助,例如sql-server-2014
。语法和功能的差异通常会影响答案。谢谢。我修正了问题中的错误并添加了额外的标签。非常感谢。工作起来很有魅力!由于是sql server 2012,我尝试了这两种方法,第二种方法的速度要快得多。
╔════════════════════╦═════════════════════╦═════════════════╗
║ MeasurementPointID ║ timestamp ║ changeDivPeriod ║
╠════════════════════╬═════════════════════╬═════════════════╣
║ 001234 ║ 2015-03-01 00:02:03 ║ 0 ║
║ 001234 ║ 2015-03-01 00:02:08 ║ 4 ║
║ 001234 ║ 2015-03-01 00:02:13 ║ 2 ║
║ 001234 ║ 2015-03-01 00:02:19 ║ 5 ║
║ 001234 ║ 2015-03-01 00:02:22 ║ 13.333333333333 ║
║ 001236 ║ 2015-03-01 00:02:04 ║ 0 ║
║ 001236 ║ 2015-03-01 00:02:09 ║ 1 ║
║ 001236 ║ 2015-03-01 00:02:14 ║ 3 ║
║ 001236 ║ 2015-03-01 00:02:19 ║ 5 ║
║ 001236 ║ 2015-03-01 00:02:25 ║ 4.166666666666 ║
╚════════════════════╩═════════════════════╩═════════════════╝
SELECT
MeasurementPointID,
[timestamp],
[changeDivPeriod] = COALESCE(1.0 * ([value] - LAG ([value]) OVER ( PARTITION BY MeasurementPointID ORDER BY [timestamp] ))
/ NULLIF(DATEDIFF(second, LAG ([timestamp]) OVER ( PARTITION BY MeasurementPointID ORDER BY [timestamp]), [timestamp]),0),0)
FROM #tab