如何在 SQL 中使用数据透视表?

问题描述

我有一张如下所示的表格:

enter image description here

需要将其转换为以下格式:

enter image description here

数据处于A、B、C级别。如下所示尝试使用 case,但结果是多行。所以考虑使用枢轴。

Select a,b,c,case when D = N and E = 1 then N1 = value,case when D = N and E = 2 then N2 = value,case when D = O and E = 1 then O1 = value,case when D = O and E = 2 then O2 = value,

任何帮助将不胜感激。谢谢!

解决方法

使用聚合:

Select a,b,c,max(case when D = 'N' and E = 1 then value end) as N1,max(case when D = 'N' and E = 2 then value end) as N2,max(case when D = 'O' and E = 1 then value end) as O1,max(case when D = 'O' and E = 2 then value end) as O2
from t
group by a,c;

请注意,这也修复了 case 表达式中的逻辑。