在SQL Server上创建数据透视时出错

时间:2018-06-06 03:03:37

标签: sql-server pivot

我在SQL Server上创建数据透视表时最后面临错误。 以下是代码:

SELECT 
    COL1, 'X'
FROM
    (SELECT COL1, COL2
     FROM TABLE_X 
     WHERE COL3 = 'B' AND COL4 = 'Activation') AS SourceTable
PIVOT
    (COUNT(COL1)
     FOR COL2 IN ('X')
    ) AS PivotTable

错误:

  

' X'

附近的语法不正确

提前致谢。

1 个答案:

答案 0 :(得分:0)

Pivot结果中不存在列COL1,因为它是Aggregated列。

您可以将此示例更改为

SELECT 
    *
FROM
    (SELECT COL1, COL2
     FROM TABLE_X 
     WHERE COL3 = 'B' AND COL4 = 'Activation') AS SourceTable
PIVOT
    (COUNT(COL1)
     FOR COL2 IN ([X]) -- put the values in square brackets instead of single quote
    ) AS PivotTable

并且您应该只获得一个名为X

的列