SQL 所有 ID 的最新变量

SQL Most Recent Variables for all IDs

系统有大约 150 个传感器,试图查询所有传感器的最新更新行 - 因此查询中的行数 = 数据库中的传感器 ID 数。下面的代码没有按预期运行,因为 V1/V2/V3/Lat/Long 的 MAX 变量不是最新的,它是所有更新中的最大值。只是寻求帮助以找到这些变量的最新信息。

Max_Timestamp 用于查找最新的变量,只是不确定如何准确获取该特定行的变量。

SELECT [SensorId]
      ,MAX(TimeStamp) AS MAX_Timestamp /* Most recent Occurence */
      ,MAX(Description) AS MAX_Description /*Doesn't change*/
      ,MAX(Type) AS MAX_Type /*Doesn't Change*/
      ,MAX(V1) AS MAX_V1 /*Need most recent variable not MAX*/
      ,MAX(V2) AS MAX_V2 /*Need most recent variable not MAX*/
      ,MAX(V3) AS MAX_V3 /*Need most recent variable not MAX*/
      ,MAX(Latitude) AS MAX_Lat /*Need most recent variable not MAX*/
      ,MAX(Longitude) AS MAX_Long /*Need most recent variable not MAX*
  FROM [IoTDB].[dbo].[IOT]
  GROUP BY SensorId
  ORDER BY SensorId

MS Sql 服务器支持 TOP(1) WITH TIES 功能

SELECT TOP(1) WITH TIES [SensorId]
      ,Timestamp 
      ,Description 
      ,Type 
      ,V1 
      ,V2 
      ,V3 
      ,Latitude
      ,Longitude
  FROM [IoTDB].[dbo].[IOT]
  ORDER BY row_number() over(partition by SensorId order by Timestamp desc);

一种方法是将其分解为两个操作:

使用 MAX(TimeStamp) 查找最近出现的事件并将其存储在临时文件中 table:

SELECT [SensorId]
      ,MAX(TimeStamp) AS MAX_Timestamp /* Most recent Occurence */
  INTO #mostRecentOccurence
  FROM [IoTDB].[dbo].[IOT]
  GROUP BY SensorId

加入这个回到原来的table:

SELECT iot.[SensorId]
      ,mr.MAX_Timestamp 
      ,iot.Description AS MAX_Description 
      ,iot.Type AS MAX_Type 
      ,iot.V1 AS MAX_V1 
      ,iot.V2 AS MAX_V2 
      ,iot.V3 AS MAX_V3 
      ,iot.Latitude AS MAX_Lat 
      ,iot.Longitude AS MAX_Long   
  FROM [IoTDB].[dbo].[IOT] iot
       INNER JOIN #mostRecentOccurence mr ON iot.SensorId = mr.SensorId
                                            AND iot.TimeStamp = mr.MAX_Timestamp
  ORDER BY iot.SensorId