PostgreSQL - 将多行返回为一行

时间:2014-08-28 17:58:09

标签: sql postgresql

我有一个返回两行的查询:

SELECT * 
FROM (
  SELECT cola,colb from table LIMIT 2
) as f

结果是:

cola, colb
x, 1
y, 2

是否可以在顶级SELECT中使用结果?类似于:

SELECT some_function(x,y), some_other_function(1,2) 
FROM (
  SELECT cola,colb from table LIMIT 2
) as f

以下是实际查询:

SELECT *
FROM
(
    SELECT 
      alt, 
      st_distance_sphere(
        st_closestpoint(geom,st_setsrid(st_makepoint(x,y),4326)),
        st_setsrid(st_makepoint(x,y),4326)
      ) as d
    FROM table
) as foo

它返回:

alt | d
800 | 9.658
900 | 11.59
etc

1 个答案:

答案 0 :(得分:1)

您需要某种交叉制表来将多行聚合为一个。

你的例子会这样:

SELECT some_function(arr_a[1], arr_a[2])
     , some_other_function(arr_b[1], arr_b[2]) 
FROM (
   SELECT array_agg(cola) AS arr_a
        , array_agg(colb) AS arr_b
   FROM   (
      SELECT cola, colb
      FROM   tbl
      ORDER  BY cola
      LIMIT  2
      ) sub1
   ) sub2;

有各种方法。取决于您的实际问题。