T-SQL使用PIVOT实现行转列失败,如何正确将属性行转为对应列?
问题原因与解决方案
你代码不生效的核心问题是PIVOT子句中指定的枚举值和源数据Type字段的实际存储值大小写不匹配:
- 源数据
Type字段存储的是小写的color、size - 你的代码IN子句中写的是大写开头的
[Color]、[Size],无法和源数据的值匹配,因此得不到正确结果
调整后的PIVOT写法
直接将IN子句的枚举值修改为和源数据一致的小写即可,需要大写开头的列名可通过别名实现:
select Name, [color] as Color, [size] as Size from ( select Name, [Type] , Attributes from @temp_table ) AS sourceTable PIVOT ( MAX(Attributes) FOR [Type] IN ([color], [size]) ) as pivot_table
备选方案(条件聚合写法,兼容性更强)
不想用PIVOT语法也可以用常规的GROUP BY+条件聚合实现,逻辑更直观,无需额外处理大小写匹配问题:
select Name, max(case when Type = 'color' then Attributes end) as Color, max(case when Type = 'size' then Attributes end) as Size from @temp_table group by Name
内容的提问来源于stack exchange,提问作者Alios
相关产品推荐
相关产品推荐

