如何在 postgresql 查询中将行转换为列
How to convert Rows to Columns in postgresql query
我有一个两行单列的简单查询输出
Virginia
Texas
我希望输出为
Virginia | Texas
我只是将它作为列列表中的两个子查询进行了尝试。
select
(select state from table where code='VA') as state1
(select state from table where code='TX') as state2
from tablename
有没有更好的方法得到结果
您在寻找字符串聚合吗?
select string_agg(state, ' | ' order by code desc)
from table
where code in ('VA', 'TX')
您可以使用条件聚合:
select max(state) filter (where code = 'VA'),
max(state) filter (where code = 'TX')
from t
where code in ('VA', 'TX')
我有一个两行单列的简单查询输出
Virginia
Texas
我希望输出为
Virginia | Texas
我只是将它作为列列表中的两个子查询进行了尝试。
select
(select state from table where code='VA') as state1
(select state from table where code='TX') as state2
from tablename
有没有更好的方法得到结果
您在寻找字符串聚合吗?
select string_agg(state, ' | ' order by code desc)
from table
where code in ('VA', 'TX')
您可以使用条件聚合:
select max(state) filter (where code = 'VA'),
max(state) filter (where code = 'TX')
from t
where code in ('VA', 'TX')