PIVOT操作员不允许使用前缀列

时间:2016-10-05 08:18:37

标签: sql sql-server tsql

我的查询如下:

select * from 
   (
     SELECT ShoperCompCode, Name, Qty, Value, Tb, ASP, UPT, AST, CTS, class2cd, CashSaleQty FROM MBDSR 
   )A
PIVOT (AVG(CashSaleQty) FOR class2cd IN ("")) AS PVT

表格如下:

ShoperCompCode  Name    Qty Value   Tb  ASP     UPT   AST    CTS    class2cd  CashSaleQty
 MB1            TEST    35  77064   6   2201.83 5.83  12844  0.44   Jeans    1
 MB2            TEST2   5   11095   2   2219    2.5   5547.5 0.06   T-shirt  2
 MB3            TEST3   0   0       0   0       0     0      0      Jeans    3

现在,我不知道它将会是什么类别的价值"牛仔裤"或" T恤"

I.e(Class2Cd数据不是静态的,它将是动态的)..

1 个答案:

答案 0 :(得分:0)

问题已解决,请检查我的更新代码。

  DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

  Select @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(Class2Cd) 
                from MBDSR
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

 set @query = 'SELECT * from 
         (
             SELECT ShoperCompCode, Name, Qty, Value, Tb, ASP, UPT, AST,       CTS, class2cd, CashSaleQty FROM MBDSR 
        ) x
        pivot 
        (
            AVG(CashSaleQty) FOR class2cd IN (' + @cols + ')
        ) p '

execute(@query);