首页 > 解决方案 > 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 服务器)

最好的,

标签: sqlsql-serverstringpivot

解决方案


使用条件聚合:

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

推荐阅读