sql - 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
……
我怎样才能达到正确的结果?
提前致谢!
解决方案
使用聚合:
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;
推荐阅读
- django - 查看 Django 表单提交是否来自管理员
- open-policy-agent - 或在 Open Policy Agent 中(联合行为)
- php - 将字符串转换为一致但随机的 10 个选项中的 1 个
- javascript - 当用户切换到完全不同的窗口时,有什么方法可以避免焦点事件?
- hadoop - hive/impala 元数据刷新
- macos - Mac 上的 WS_EX_NOACTIVATE 样式窗口
- azure - 合并 (UPSERT) - AZURE SQL DWH
- typescript - React Native 样式表合并:传播类型只能从对象类型创建
- wordpress - 在 asp.net core 2.2 应用程序中保护和集成 peachpie wordpress 安装
- java - Quarkus MySQL JDBC 依赖