我正在尝试查询以下内容:
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
但是无论我如何更改查询,都会不断出错。例如:
ERROR: syntax error at or near "as"
LINE 11: ) as b
此查询出了什么问题?
答案 0 :(得分:2)
在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;
在最新版本的Postgres中,您可以改用横向join
:
select v.currency, sum(v.volume)
from "Pairs" p cross join lateral
(values ("baseCurrency", "baseVolume"),
("quoteCurrency", "quoteVolume")
) v(currency, volume)
group by v.currency;
coalesce()
可能是不必要的。如果获得NULL
结果,则可以在sum()
之后进行处理。 。 。 coalesce(sum(volume), 0)
。
答案 1 :(得分:0)
根据ISO标准。 PostgreSQL被设计为在使用子查询时具有别名。 Go here for further information。
对于您而言,以下更改将有所帮助:
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