简体   繁体   中英

Getting latest sensor value in set of devices

I have a table with following schema:

meshSetVersion integer
gatewayMAC text
deviceMAC text
sensorID integer
sensorValue text
timestamp time

First I find the latest meshSetVersion with:

(select max(meshSetVersion) from test where gatewayMAC='XXX') as lastV

Then I find it's devices:

select distinct gatewayMAC, deviceMAC from test
where gatewayMAC='xxx' and meshSetVersion=lastV

Then I need to get latest sensorValue of each ID by timestamp

One method uses distinct on . I think this is the logic that you want:

select distinct on (sensorId) t.*
from test t
where t.meshSetVersion = (select max(t2.meshSetVersion)
                          from test t2
                          where t2.gatewayMach = 'xxx'
                         )
order by sensorId, timestamp desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM