sql - 如何在 postgresql 查询中将行转换为列

标签 sql postgresql crosstab

我有一个两行单列的简单查询输出

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')

关于sql - 如何在 postgresql 查询中将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57212285/

相关文章:

ruby-on-rails-3 - 尽管经过验证,为什么 Rails 3.2 允许重复记录?

sql - 以格林威治标准时间生成日期的所有分钟并获取其本地值

sql - sqlite3命令行返回码不一致

postgresql - Postgres : index on cosine similarity of float arrays for one-to-many search

mysql - 碧 Jade 报告 : crosstab to display null columns

python - 计算 DataFrame 中的出现次数

postgresql - 为 Postgres 交叉表动态生成 AS 子句

mysql - SQl 选择出现在一组或多组中的数据

MySQL区分大小写的插入

sql - 如何解决 raster_columns 问题?