Matt
Matt

Reputation: 7192

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? 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

Upvotes: 0

Views: 501

Answers (1)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 656251

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.

Upvotes: 1

Related Questions