sql - 如何在 postgresql 查询中将行转换为列
问题描述
我有一个两行单列的简单查询输出
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')
推荐阅读
- java - Iterating arraylist until find an specific character and stop the iteration
- sql-server - SQL Server FULL TEXT 搜索会话永久锁定
- javascript - Javascript 表单验证不起作用,不确定我哪里出错了
- excel - 如何在颤动的列表中获得所需的数据?
- flutter - 有什么方法可以在容器内显示 ImagePicker/FilePicker 对话框,而不是打开手机全屏
- r - 如何创建一个创建具有组合观察的列的函数
- node.js - 如何在mongodb中返回选定的字段?
- node.js - 如何为部署副本构建 Node.js 项目?
- algorithm - 为什么我们应该在函数之前使用 std 命名空间
标头,不应该在功能之前使用它 标题? - python - 如何在熊猫参考日期之前和之后有效地找到最近的日期?