The problem I'm trying to solve is that I have a table like this:
a and b refer to a point in another table. distance is the distance between points.
| id | a_id | b_id | distance | delete | | 1 | 1 | 1 | 1 | 0 | | 2 | 1 | 2 | 0.2345 | 0 | | 3 | 1 | 3 | 100 | 0 | | 4 | 2 | 1 | 1343.2 | 0 | | 5 | 2 | 2 | 0.45 | 0 | | 6 | 2 | 3 | 110 | 0 | ....
The important column I'm looking for is a_id. If I wanted to save cabinet b for each a, I could do something like this:
update mytable set delete = 1 from (select a_id, min(distance) as dist from table group by a_id) as x where a_gid = a_gid and distance > dist; delete from mytable where delete = 1;
Which would give me a result table as follows:
| id | a_id | b_id | distance | delete | | 1 | 1 | 1 | 1 | 0 | | 5 | 2 | 2 | 0.45 | 0 | ....
i.e. I need one row for each a_id value, and this row should have the lowest distance value for each a_id.
However, I want to save the 10 closest points for each a_gid. I could do this with the plpgsql function, but I'm curious if there is a SQL-y way.
min () and max () return the smallest and largest value, if there is an aggregate function such as nth () that returns the nth largest / smallest value, then I could do it the same way as described above.
I am using PostgeSQL.
source share