简体   繁体   English

PostgreSQL-将多行作为一个返回

[英]PostgreSQL - return multiple rows as one

I have a query that returns two rows: 我有一个查询,返回两行:

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

Result is: 结果是:

cola, colb
x, 1
y, 2

Is it possible to use the results in the top level SELECT? 是否可以在顶级SELECT中使用结果? Similar to: 如同:

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

Here is the actual query: 这是实际的查询:

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

It returns: 它返回:

alt | d
800 | 9.658
900 | 11.59
etc

You need some kind of cross-tabulation to aggregate multiple rows into one. 您需要某种交叉表才能将多行汇总为一个。

Your example would work like this: 您的示例将如下所示:

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;

There are various ways. 有多种方法。 Depends on your actual problem. 取决于您的实际问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM