PIVOT和TEMP表

时间:2014-04-10 13:45:51

标签: sql pivot temp

请帮我把这个脚本放到临时表中。我一直在努力工作几个小时,它一直给我错误。

    DECLARE @PivotColumnHeaders VARCHAR(MAX)
    SELECT @PivotColumnHeaders = 
    COALESCE(@PivotColumnHeaders + ',[' + CAST(expansion as varchar(max)) + ']',
    '[' + CAST(expansio

    n as varchar(max))+ ']')

INTO #temp
FROM (Select distinct expansion from #CD4_VL2) results


DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
select * from
(
select subjectID,expansion,printableValue1
from #CD4_VL2) as results


PIVOT

(MAX([printableValue1])
FOR [expansion] IN (
' + @PivotColumnHeaders + '
)
) as PivotTable

--order by Performed_Date_And_Time desc
'

Execute(@PivotTableSQL )

1 个答案:

答案 0 :(得分:0)

由于您已在扩展列上进行了调整,因此MAX(printableValue1)的相应值现在将位于Expansion列中包含数据名称的列中。改变这样:

DECLARE @PivotColumnHeaders NVARCHAR(MAX) = 'Expansion1, Expansion2, Expansion3';

DECLARE @PivotTableSQL NVARCHAR(MAX);
SET @PivotTableSQL = 
N'select subjectID, ' + @PivotColumnHeaders 
+' from #CD4_VL2 
  PIVOT
(
  MAX([printableValue1])
  FOR [expansion] IN (' + @PivotColumnHeaders + ')) x';

Execute(@PivotTableSQL);

SqlFiddle here