Given a table that looks like this:
sensor_id | time | voltage
-----------+------------------------+------------
12292 | 2009-12-01 00:50:04-07 | 2270
12282 | 2009-12-01 00:50:04-07 | 93774
12192 | 2009-12-01 00:50:04-07 | 9386
12609 | 2009-12-01 00:50:05-07 | 0
12566 | 2009-12-01 00:50:08-07 | 0
12659 | 2009-12-01 00:50:19-07 | 540
12660 | 2009-12-01 00:50:19-07 | 550
12661 | 2009-12-01 00:50:19-07 | 510
12656 | 2009-12-01 00:50:19-07 | 30240
12657 | 2009-12-01 00:50:19-07 | 14930
12658 | 2009-12-01 00:50:19-07 | 17420
11820 | 2009-12-01 00:50:26-07 | 1.38
11832 | 2009-12-01 00:50:28-07 | 1.359
12768 | 2009-12-01 00:50:33-07 | 636588
13192 | 2009-12-01 00:50:34-07 | 1.401
. . .
. . .
. . .
There are times when you will get records looking like:
12292 | 2009-12-01 00:50:04-07 | 2270
12282 | 2009-12-01 00:50:04-07 | 93774
12192 | 2009-12-01 00:50:04-07 | 9386
12609 | 2009-12-01 00:50:05-07 | 0
12566 | 2009-12-01 00:50:08-07 | 0
12659 | 2009-12-01 00:50:19-07 | 540 *
12659 | 2009-12-01 00:50:45-07 | 541 *
12660 | 2009-12-01 00:50:19-07 | 550
12661 | 2009-12-01 00:50:19-07 | 510
12656 | 2009-12-01 00:50:19-07 | 30240
12657 | 2009-12-01 00:50:19-07 | 14930
12658 | 2009-12-01 00:50:19-07 | 17420
11820 | 2009-12-01 00:50:26-07 | 1.38 #
11832 | 2009-12-01 00:50:28-07 | 1.359
11820 | 2009-12-01 00:50:28-07 | 1.3 #
12768 | 2009-12-01 00:50:33-07 | 636588
13192 | 2009-12-01 00:50:34-07 | 1.401
. . .
. . .
. . .
Notice the stared and hashed lines. Each are readings taken in the same minute, but i need only one value per minute, preferably the max value. I tried:
select sensor_id, read_time, voltage
from table
where (sensor_id, read_time)
in (select sensor_id, max(read_time)
from table
group by sensor_id);
This obviously doesn't work, but I think I'm on the right track?
For those interested the final code looks like:
select sensor_id, date_trunc('minute', read_time), max(voltage)
from table
group by sensor_id, date_trunc('minute', read_time)
order by date_trunc('minute', read_time);