Postgres,找到数组列的最小值并获取其位置

时间:2017-02-15 14:48:45

标签: arrays postgresql

让我们假设下表:test

ids | l_ids      |  distance
-----------------+-----------
 53 | {150,40}   | {1.235, 2.265}
 22 | {20,520}   | {0.158, 0.568}

两个数组的位置(l_ids,distance)是相互依赖的,意思是 150对应1.235, 40对应于2.265等等。

我想获得最小距离和相应的l_id。因此结果应该是这样的:

   ids | l_ids      |  distance
   ----------------+-----------
    53 |  150       |  1.235
    22 |   20       |  0.158

通过运行:

select l_ids, min(dist) as min_distance 
from test, unnest(test.distance) dist
group by 1; 

结果是:

     l_ids      |  dist
    ------------+-----------
     {150,40}   |  1.235
     {20,520}   |  0.158

我想获取距离数组中最小值的位置,以便从l_ids数组中获取相应的id。

任何指南?提前谢谢

3 个答案:

答案 0 :(得分:2)

SELECT DISTINCT ON (ctid) l_ids, distance
FROM (SELECT ctid,
             unnest(l_ids) AS l_ids,
             unnest(distance) AS distance
      FROM test
     ) q
ORDER BY ctid, distance;

 l_ids | distance
-------+----------
   150 |    1.235
    20 |    0.158
(2 rows)

答案 1 :(得分:2)

如果id是唯一的标识符,并且distance数组中没有重复的值,则应该有效:

SELECT a.* from  
(SELECT ids, UNNEST(l_ids) AS l_ids, UNNEST (distance) AS distance  FROM test) a
INNER JOIN (SELECT ids, MIN(distance) as mind FROM (
        SELECT ids,  UNNEST (distance) AS distance  FROM test 
    ) t
GROUP BY ids ) t
ON
a.ids = t.ids and a.distance = t.mind

答案 2 :(得分:1)

从9.4开始,您可以使用UNNEST()'s special ROWS FROM()-like syntax

select   distinct on (ids) ids, l_id, dist min_distance
from     test, unnest(l_ids, test.distance) d(l_id, dist)
order by ids, dist

否则,这是典型的查询。