Postgres - Subtraction of two queries

13,981

The following query will join a one-row result set against a many row result set, and allow them to be compared.

SELECT
    a.*,
    b.*,
    a.distance_km - b.distance_kn    AS difference
FROM
(
    SELECT  ST_Y(ST_Centroid(ST_Collect(column1))) AS distance_km FROM table1
)
    a
CROSS JOIN
(
    SELECT ST_Y(ST_Transform(column1,4326)) AS distance_km FROM table1
)
    b
Share:
13,981
PRVS
Author by

PRVS

I'm a junior programmer. Always looking for new challenges.

Updated on June 17, 2022

Comments

  • PRVS
    PRVS almost 2 years

    I want to make a subtraction like this:

    SELECT 
        (SELECT ST_Y(ST_Centroid(ST_Collect(column1))) AS distance_km 
         FROM table1) - 
        (SELECT ST_Y(ST_Transform(column1,4326)) AS distance_km 
         FROM table1) AS Difference
    

    But the ST_Y(ST_Centroid(ST_Collect(column1))) has only one row and ST_Y(ST_Transform(column1,4326)) has multiple rows. I want to subtract the multiple rows by the column and see the results for each multiple row. With this query I get:

    ERROR: more than one row returned by a subquery used as an expression

    Any help?

  • MatBailie
    MatBailie almost 8 years
    @PRVS - Sub-queries and CROSS JOIN are ANSI-SQL. So, yes, it works in PostGreSQL.
  • a_horse_with_no_name
    a_horse_with_no_name almost 8 years
    @MatBailie: the name is either spelled PostgreSQL or just Postgres. Never with a capital G