1

I am trying to query the following:

select currency, sum(volume)
from
    (
        select "baseCurrency" as currency,
               COALESCE("baseVolume", 0) as volume
        from "Pairs"
    )  as a
    union all
    (
        select "quoteCurrency" as currency,
               COALESCE("quoteVolume", 0) as volume
        from "Pairs"
    ) as b
group by currency

But keeps getting errors no matter how I changed the query. For example:

ERROR:  syntax error at or near "as"
LINE 11:  ) as b

What is wrong in this query?

2 Answers 2

2

Don't use aliases for the subqueries in a union all:

select currency, sum(volume)
from ((select "baseCurrency" as currency, COALESCE("baseVolume", 0) as volume
       from "Pairs"
       ) union all
       (select "quoteCurrency" as currency, COALESCE("quoteVolume", 0) as volume
        from "Pairs"
       ) 
      ) c
group by currency;

In more recent versions of Postgres, you can use a lateral join instead:

select v.currency, sum(v.volume)
from "Pairs" p cross join lateral
     (values ("baseCurrency", "baseVolume"),
             ("quoteCurrency", "quoteVolume")
     ) v(currency, volume)
group by v.currency;

The coalesce() is probably unnecessary. If you are getting NULL results, you can handle it after the sum() . . . coalesce(sum(volume), 0).

Sign up to request clarification or add additional context in comments.

2 Comments

Regarding your last comment, putting coalesce out of the sum will make a problem since 3443+null equals null.
@Naor . . . No. Aggregation functions ignore NULL values.
0

It is according to ISO standards. PostgreSQL was designed to have aliases when subqueries are used. Go here for further information.

In your case the following change will help:

select b.currency, b.sum(volume)
from
  (  (
        select "baseCurrency" as currency, COALESCE("baseVolume", 0) as volume
        from "Pairs"
    )  
    union all
    (
        select "quoteCurrency" as currency, COALESCE("quoteVolume", 0) as volume
        from "Pairs"
    ) )as b
group by currency

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.