首页 > 解决方案 > 选择每组中的最后一个值

问题描述

在数据库中,我有两个表。我想加入两个表并获得最后一行SensorType

传感器表:

ID 代码编号 端口号 传感器类型 活跃
13 DHT11 3 0 1
14 DHT11 3 2 1
17 全球的 100 4 1
18 DHT11 3 1 1
19 DHT11 3 3 1

SensorsValue 表(SensorId是外键 Sensors 表):

ID 传感器 ID 价值 DateOfRetrevingValue
19 13 25 2021-07-23 08:50:27.0000000
20 14 45 2021-07-23 09:50:27.0000000
21 17 12 2021-07-23 10:50:27.0000000
22 18 24 2021-07-23 11:50:27.0000000
23 19 45 2021-07-23 12:50:27.0000000
24 13 23 2021-07-23 13:50:27.0000000
25 14 56 2021-07-23 14:50:27.0000000
26 17 23 2021-07-23 15:50:27.0000000
27 18 34 2021-07-23 16:50:27.0000000
28 19 23 2021-07-23 17:50:27.0000000

我想加入两个表并SensorTypeSensors表和最后一个Value(从SensorsValue)中选择SensorType。在这种情况下,我想得到结果:

|SensorType|Value|
|----------|-----|
|    0     | 23  |
|    2     | 56  |
|    4     | 23  |
|    1     | 34  |
|    3     | 13  |

我找到了这篇文章并使用了这个声明:

SELECT distinct Sensor.Type, MAX(SensorValues.Id), SensorValues.Value
FROM Sensor
INNER JOIN SensorValues ON Sensor.Id=SensorValues.SensorId
GROUP BY Sensor.Type

但我得到了错误:

选择列表中的“SensorValues.Value”列无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

如果我在没有SensorValues.Value查询工作的情况下使用此语句,但我得到了结果:

|SensorType|Id|
|----------|--|

标签: sqlsql-servertsql

解决方案


你应该使用first_value

select distinct t1.SensorType,
       first_value(t2.value) over(partition by t1.SensorType order by t2.DateOfRetrevingValue desc)
  from Sensors t1,
       SensorsValue t2
 where t1.id = t2.SensorId

推荐阅读