2016-01-13 91 views
0

SQL數據透視表和動態SQL的新功能。我有一個表格,我希望使不同的屬性成爲數據透視表中的列標題,同時還爲主數據創建正確的主要類別,並在這些字段中報告分數。問題是我無法獲得正確填充的分數或不同的列標題。支持多列動態SQL的數據透視表

我無法使Measure1字段成爲列標題,我無法獲得分數來填充。使用與Measure1和相關分數相關的正確[度量名稱]。感謝您提前提供任何幫助。

Declare @ColumnNames NVARCHAR (MAX) = '' 
Declare @SQL NVARCHAR (MAX)= '' 

Select @ColumnNames += QUOTENAME([Measure1]) + ',' 
From [dbo].[Table1] 

Group By [Measure1] 

SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1) 
SET @SQL = 
'Select * FROM 
(Select 
    case 
     When [measure1] like ''%lower%'' then ''Lower'' 
     When [measure1] like ''%upper%'' then ''Upper'' 
     When [measure1] like ''%Days%'' then ''Days'' 
     When [measure1] like ''%Occur%'' then ''Occurrences'' 
     When [measure1] like ''%Pred%'' then ''Predicted'' 
     When [measure1] like ''%Ratio%'' then ''Ratio'' 
     end as [Measure1] 
    ,case 
     When [Measure Name] like ''%Tewksbury%'' then ''Stan'' 
     When [Measure Name] like ''%Boston%'' then ''Steve'' 
     When [Measure Name] like ''%Seattle%'' then ''Payton'' 
     When [Measure Name] like ''%Denver%'' then ''Lavell'' 
     When [Measure Name] like ''%Houston%'' then ''Caren'' 
     When [Measure Name] like ''%Hudson%'' then ''Michael'' 
     end as Measure_Category 
    ,[Main ID] AS [Cust ID] 
    ,[Compared to Average] 
    ,[score] 

From 
    [dbo].[Table1] 
) AS BaseData 

PIVOT (
    MAX([Compared to Average]) 
    FOR [measure1] 
    IN (' + @ColumnNames + 

')) AS PivotTable' 



Execute sp_executesql @SQL 

實際結果: enter image description here

期望的結果: enter image description here

關閉了預期的效果: enter image description here

+1

能否請您發佈您獲得的結果以及您的期望? –

+0

是的,抱歉,我應該包括這個。 –

回答

1

嗯,你@ColumnNames PARAM不匹配,你實際上在做什麼在您的數據透視查詢中進行選擇,因此您可能需要將您的@ColumnNames param更改爲某些這樣的事情,而不是。

SELECT @ColumnNames = COALESCE(@ColumnNames + ',','') + QUOTENAME([Measure1]) 
FROM (SELECT DISTINCT 
       CASE WHEN [measure1] LIKE '%lower%' THEN 'Lower' 
        WHEN [measure1] LIKE '%upper%' THEN 'Upper' 
        WHEN [measure1] LIKE '%Days%' THEN 'Days' 
        WHEN [measure1] LIKE '%Occur%' THEN 'Occurrences' 
        WHEN [measure1] LIKE '%Pred%' THEN 'Predicted' 
        WHEN [measure1] LIKE '%Ratio%' THEN 'Ratio' 
       END AS [Measure1] 
     FROM [dbo].[Table1] 
     ) t 
WHERE [Measure1] IS NOT NULL 

你可以離開這個。

SET @ColumnNames = LEFT(@ColumnNames, LEN(@ColumnNames)-1)