Incompatible Pivot Type SQL

前端 未结 1 1743
逝去的感伤
逝去的感伤 2021-01-22 22:49

I have been given a database I need to perform a PIVOT on. My Pivot works perfectly fine. However, one of the columns I need to perform in my SELECT is a column

1条回答
  •  太阳男子
    2021-01-22 23:06

    My personal preference would be just to convert the column type to VARCHAR(MAX) and be done with it, TEXT is on the deprecation list anyway.

    If this is not an option you can simply cast/convert the text value to VARCHAR(MAX) in your query. e.g.

    CREATE TABLE #T (A TEXT, B CHAR(1), Val INT);
    INSERT #T (A, B, Val)
    VALUES ('A', '1', 1), ('A', '2', 3), ('A', '3', 2);
    
    SELECT  pvt.A, pvt.[1], pvt.[2], pvt.[3]
    FROM    #T
            PIVOT 
            (   SUM(Val)
                FOR B IN ([1], [2], [3])
            ) pvt;
    

    Gives the error:

    Msg 488, Level 16, State 1, Line 6

    Pivot grouping columns must be comparable. The type of column "A" is "text", which is not comparable.

    This works fine:

    SELECT  pvt.A, pvt.[1], pvt.[2], pvt.[3]
    FROM    (   SELECT A = CAST(A AS VARCHAR(MAX)), B, Val
                FROM #T
            ) t
            PIVOT 
            (   SUM(Val)
                FOR B IN ([1], [2], [3])
            ) pvt;
    

    0 讨论(0)
提交回复
热议问题