SQL用CASE WHEN旋转字段

问题描述 投票:0回答:1

我的表中包含以下字段:项目,AttributeNo_,AttrbuteValue。每个AttributeNo_都有一个匹配的AttributeName。

例如

Item, AttributeNo_, AttributeValue
A,    1,            Yellow
A,    2,            Round
……

((AttributeNo_ 1表示颜色,2表示形状作为AttributeName)

这是我要实现的目标:

Item, Color,  Shape
A,    Yellow, Round
……

我的代码是:

select Item, 
case when AttributeNo_=1 then AttributeValue end AS Color,
case when AttributeNo_=2 then AttributeValue end AS Shape
from table;

结果类似于:

Item, Color,  Shape
A,    Yellow, Null
A,    Null,   Round
……

如何获得正确的结果?

提前感谢!

sql
1个回答
0
投票

使用聚合:

select Item, 
       max(case when AttributeNo_ = 1 then AttributeValue end) AS Color,
       max(case when AttributeNo_ = 2 then AttributeValue end) AS Shape
from table
group by Item;
© www.soinside.com 2019 - 2024. All rights reserved.