sql - SQL 列名作为行值
问题描述
我有一个包含“区域”、“目标”和“实际”列的表格,如下所示。
地区 | 目标 | 实际的 |
---|---|---|
一个 | 10 | 1 |
乙 | 20 | 2 |
我想用我的查询更改这个表,以便目标列和实际列在行中,如下所示。
地区 | 类型 | 数量 |
---|---|---|
一个 | 目标 | 10 |
一个 | 实际的 | 1 |
乙 | 目标 | 20 |
乙 | 实际的 | 2 |
我应该如何为此准备查询或应该使用哪种方式?提前致谢。
解决方案
您可以为此使用 UNION:
select region, 'Target' as type, target as amount
from the_table
union all
select region, 'Actual' as type, actual
from the_table
order by region, type desc
另一种选择是使用横向连接从列中构造两行:
select t.region, x.*
from the_table t
cross join lateral (
values ('Target', target), ('Actual', actual)
) as x(type, amount)
order by t.region, x.type desc;
这两个查询都是 100% 的标准 ANSI SQL。然而,并非所有数据库产品都支持横向连接或VALUES
类似的子句。
推荐阅读
- linux - Bash:读取 CSV 文本文件并查找行的平均值
- sql-server - SQL CASE WHEN - 返回不需要的行的 NULL 值
- shibboleth - Shibboleth:“元数据根元素未签名,需要签名”
- android - 从Play商店下载时,颤动的谷歌登录无法在发布中工作
- php - 提交电子邮件表单后尝试在 PHP 中重定向
- sql-server - 将已处理的文件移动到年、月、日文件夹树备份文件夹 (SSIS)
- python - RuntimeError:梯度计算所需的变量之一已被就地操作修改:PyTorch 错误
- linux - 管道定位命令和 md5 输出不同的校验和值
- ruby-on-rails - 在没有 Rails 的情况下使用 Active Storage
- react-native - 一旦 cocoapods 从 Podfile 安装 react-native-mapbox-gl,Xcode 就会成功构建损坏的存档,而不显示在管理器中