我有两个表需要加入一个select语句,它只能给我每个sensorID的最后一行(每个sensorID的最新值)。这是我的表格:
sensorID| Name | Description | stationID
---------------------------------
1 | Name1 | Desc1 | 2
2 | Name2 | Desc2 | 1
3 | Name3 | Desc3 | 3
4 | Name4 | Desc4 | 2
值
vID | sensorID | Date | Time | value
---------------------------------
1 | 1 | 2016-12-29 | 15:08:00 | 0.2
2 | 1 | 2016-12-29 | 15:10:00 | 0.21
3 | 1 | 2016-12-29 | 15:12:00 | 0.4
4 | 4 | 2016-12-29 | 15:14:00 | 12.2
我尝试运行以下内容:
SELECT * FROM H INNER JOIN Values V ON H.sensorID = V.sensorID WHERE H.stationID = 2;
产生了这些结果:
sensorID | Name | Description | stationID | vID | sensorID | Date | Time | value
1 | Name1| Desc1 | 2 | 1 | 1 |2016-12-29 | 15:08:00 | 0.2
1 | Name1| Desc1 | 2 | 2 | 1 |2016-12-29 | 15:10:00 | 0.21
1 | Name1| Desc1 | 2 | 3 | 1 |2016-12-29 | 15:12:00 | 0.4
4 | Name4| Desc4 | 2 | 4 | 1 |2016-12-29 | 15:14:00 | 12.2
但我正在寻找这个输出:
sensorID | Name | Description | stationID | vID | sensorID | Date | Time | value
1 | Name1| Desc1 | 2 | 3 | 1 |2016-12-29 | 15:12:00 | 0.4
4 | Name4| Desc4 | 2 | 4 | 1 |2016-12-29 | 15:14:00 | 12.2
答案 0 :(得分:3)
如果你想要每个传感器的最后一行,我倾向于使用id
列而不是日期/时间:
SELECT *
FROM H INNER JOIN
Values V
ON H.sensorID = V.sensorID
WHERE H.stationID = 2 AND
V.id = (SELECT MAX(v2.id) FROM Values v2 WHERE v2.SensorId = v.SensorId);
此版本可以充分利用Values(SensorId, id)
上的索引。
答案 1 :(得分:1)
尝试这个
sensorID Name DescR stationID vID sensorID DateD TimeD value sensorID dateT
1 Name1 Desc1 2 3 1 2016-12-29 15:12:00.0000000 0.4 1 2016-12-2915:12:00.0000000
4 Name4 Desc4 2 4 4 2016-12-29 15:14:00.0000000 12.2 4 2016-12-2915:14:00.0000000
输出
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY salary ASC) AS row number
FROM pact
) as temp table name
WHERE rownumber IN (2,5)