首页 > 解决方案 > SQL 使用 CASE WHEN 旋转字段

问题描述

我的表有字段:Item、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

解决方案


使用聚合:

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;

推荐阅读