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?
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)
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.