T-SQL Pivot错误:“ 0”附近的语法不正确

时间:2018-09-22 22:23:29

标签: sql-server tsql pivot

我不确定我的代码在做什么错。我收到一条错误消息:

  

第15层状态1的第82行的消息102
  '0'附近的语法不正确

有人可以帮我找出我的错误吗?我正在尝试透视表,以便查询返回带有年龄组而不是行的标头。

SELECT *
FROM 
    (SELECT
         ID,
         CASE 
            WHEN Age BETWEEN 0 AND 4 THEN '0-4 Years'
            WHEN  Age  BETWEEN 5 AND 24 THEN '5-24 Years' 
            WHEN Age BETWEEN 25 AND 49 THEN '25-49 Years'
            WHEN Age BETWEEN 50 AND 64 THEN '50-64 Years'
            WHEN Age > 64 THEN '> 64 Years'
        END AS GroupAge
    FROM 
        #AD) t
PIVOT
    (COUNT(ID)
         FOR GroupAge IN 
             (0-4 Years,5-24 Years,25-49 Years,> 64 Years)
    ) AS pvt

2 个答案:

答案 0 :(得分:4)

在数据透视表的列名周围放置方括号[]。

PIVOT
(
    COUNT(ID)
    FOR GroupAge IN 
    ([0-4 Years],[5-24 Years],[25-49 Years],[50-64 Years],[> 64 Years])
) AS pvt

答案 1 :(得分:1)

该错误导致您需要在枢轴列中使用方括号,因为0-4 Years ..列不是普通字符串。

我将使用条件聚合函数进行透视。

SELECT
    COUNT(CASE WHEN Age BETWEEN 0 AND 4 THEN  ID END) '0-4 Years', 
    COUNT(CASE WHEN Age BETWEEN 5 AND 24  THEN  ID END) '5-24 Years' , 
    COUNT(CASE WHEN Age BETWEEN 25 AND 49 THEN  ID END) '25-49 Years', 
    COUNT(CASE WHEN Age BETWEEN 50 AND 64 THEN  ID END) '50-64 Years', 
    COUNT(CASE WHEN  Age > 64 THEN  ID END) '> 64 Years'
FROM #AD