如何在 SQL 中使用数据透视表?
How to use pivot in SQL?
我有一个 table 如下所示:
需要将其转换成以下格式:
数据为A、B、C级别。尝试使用 case when 如下所示,但它会导致多行。所以想用一个pivot。
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, b, c;
请注意,这也修复了 case
表达式中的逻辑。
我有一个 table 如下所示:
需要将其转换成以下格式:
数据为A、B、C级别。尝试使用 case when 如下所示,但它会导致多行。所以想用一个pivot。
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, b, c;
请注意,这也修复了 case
表达式中的逻辑。