如何将表行转换为具有动态名称的列

时间:2014-01-23 10:16:46

标签: sql tsql pivot

我正在努力想弄明白怎么做

CID  sUSER  VALUE
------------------
001  235      10
001  188      20
001   04      5
002  235      11
002  188      12
002   04      13

我希望它显示如下

CID  04   188  235
-------------------
001  5     20   10
002  13    12   11

有人可以请给我看一下Sql代码吗?

2 个答案:

答案 0 :(得分:0)

让我们假设你已经在#tmpCID中过滤了数据;现在尝试下面的脚本

Declare @sUser As Varchar(Max)
SELECT @sUser= Case isNull(@sUser,'')
        When '' then '['+ Rtrim(sUser) + ']'
        Else  COALESCE(@sUser + ',[', ',') +  Rtrim(sUser)+ ']'
        End
         FROM (SELECT DISTINCT sUser FROM #tmpCID) U


Declare @Query As Varchar(Max)
Set @Query='Select CID, ' + @sUser + ' From #tmpCID
    Pivot (AVG(Value)
    For sUser IN     ('+ @sUser + ')) As P'

EXEC  (@Query)

答案 1 :(得分:0)

试试这个:

CREATE PROCEDURE YourProcedureName
as
Begin 

DECLARE @sUSER AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @sUSER = STUFF((SELECT distinct ',' + QUOTENAME(sUSER) FROM testPIVOT
                      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '');


SELECT @query = 'WITH PivotData AS
(
   SELECT CID, sUSER, VALUE
   FROM dbo.YourTableName
)

SELECT CID, '+ @sUSER +'
FROM PivotData
PIVOT(max(VALUE) FOR sUSER IN('+ @sUSER +')) AS P;';

execute(@query);

End

希望它可以帮到你!

感谢。