I'm using PostgreSQL.
I want to select 1 row for every unique id, I have this query:
SELECT DISTINCT ON (station_id) *
FROM readings
ORDER BY station_id,reading_id DESC;
I have 2 tables:
readings
(content isn't important, I hope):
station_id reading_id temp air_pressure
--------------------------------------------
147 100 10 800
148 101 20 850
149 102 30 900
148 103 40 950
148 104 50 1000
147 105 60 1050
stations
(content not important I hope):
id station_name lat lng
-----------------------------
147
148
149
So readings.station_id
and station.id
in stations should be the same.
My query works, but now I want to select the second newest one (2nd highest id): ignore the first row (newest reading) and select the second.
Desired result based on above sample:
station_id reading_id temp air_pressure
----------------------------------------------
148 103 40 950
147 100 10 800
I want the row with the second highest reading_id
for every station_id
(second newest reading).
Would be nice if it won't select the ones where there is only one row, but not necessary.
I'm not sure how to achieve this. I've tried so much with offset
, limit
etc. also tried some nested select queries ...
I want to use distinct on
because I need to select second row from every unique id. But if it's not possible with distinct on
, it's alright.