sql - SQL Server如何根据列值展开表
问题描述
我有一张看起来像这样的桌子
+----+------+------+-------+
| ID | FY | Code | Value |
+----+------+------+-------+
| 1 | 2021 | A | 2 |
+----+------+------+-------+
| 1 | 2021 | B | 5 |
+----+------+------+-------+
| 1 | 2021 | C | 3 |
+----+------+------+-------+
| 2 | 2021 | A | 4 |
+----+------+------+-------+
| 2 | 2021 | B | 5 |
+----+------+------+-------+
| 2 | 2021 | C | 6 |
+----+------+------+-------+
我想将代码列扩展为以下格式:
+----+------+---+---+---+
| ID | FY | A | B | C |
+----+------+---+---+---+
| 1 | 2021 | 2 | 5 | 3 |
+----+------+---+---+---+
| 2 | 2021 | 4 | 5 | 6 |
+----+------+---+---+---+
我想出了一个丑陋的方法来使用多个 Where 子查询并将它们连接在一起,但是“代码”列中有一些值使事情变得丑陋。
有没有一种优雅的方式来实现这一目标?(SQL 服务器)
最好的,
解决方案
使用条件聚合:
select
id,
fy,
max(case when code = 'A' then value end) as A,
max(case when code = 'B' then value end) as B,
max(case when code = 'C' then value end) as C
from mytable
group by id, fy
推荐阅读
- c# - 如何以最有效的方式更改多个按钮上的文本,而无需在 C# 中重复代码?
- python - 如何使用 python 请求发送表单数据?
- r - 如何按项目计算分类变量的百分比?
- swift - 如何在不使用 Any 的情况下在 Swift 中存储具有关联类型的协议数组?
- c++ - 如何在不复制的情况下在结构中使用来自 stl 的容器
- highcharts - 为什么在使用 400 个数据点时会出现“无法读取未定义的属性 'isValid'”?
- python - 如何修复 open-ai 健身房中的环境错误?
- c++ - 如何使用 mingw-w64 的 Visual Studio 静态库?
- android - 如何使用“git cherry-pick”手动更新自定义 rom 的安全补丁?
- python - 如何使用 plotly express 创建子图?