在同一列SQL上的多个数据透视图中将数据类型nvarchar转换为int时出错

时间:2018-09-19 20:55:20

标签: sql sql-server tsql ssms

我正在尝试在同一列的单个查询中使用多个数据透视。 由于我对所有数据透视表都使用相同的“月”列,因此我已将列标题添加到选择列表中,并添加了不同的别名。月列具有int数据类型值。下面是代码:

    Select * FROM  
    (
    SELECT 
    [team], 
    Count_O,
    Count_Of_OA,
    Avg,
    [month]+ '_a'  as month_a, 
    [month] + '_b' as month_b,
    [users]  
    FROM [#Temp]
    ) AS X 

    PIVOT  
(  
    MAX(Count_OA)
    FOR [month_a] IN ([4_a], [5_a], [6_b])  
)   AS PivotTable1

PIVOT  
(  
    MAX(Count_O)
    FOR [month_b] IN ([4_b], [5_b], [6_b])  
)   AS PivotTable2

执行此操作时,出现以下错误: 讯息8114,第16级,州1,第44行 将数据类型nvarchar转换为int时出错。

任何输入将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试一下

Select * FROM  
    (
    SELECT 
    [team], 
    Count_O,
    Count_Of_OA,
    Avg,
    Convert(varchar(max),[month])+ '_a'  as month_a, 
    Convert(varchar(max),[month]) + '_b' as month_b,
    [users]  
    FROM [#Temp]
    ) AS X 

PIVOT  
(  
    MAX(Count_OA)
    FOR [month_a] IN ([4_a], [5_a], [6_b])  
)   AS PivotTable1

PIVOT  
(  
    MAX(Count_O)
    FOR [month_b] IN ([4_b], [5_b], [6_b])  
)   AS PivotTable2