You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:15:04