2017-07-30 57 views
0

我仍然是一個初學者與T-SQL有什麼是一個相對簡單的選擇語句與幾個聯接。我試圖把它放到一個動態數據透視表中。本聲明的目的在於展示非營利性服務及其結果,新舊結果僅僅是同一數據的不同詞彙。試圖找出如何做一個動態的數據透視表與連接

SELECT Service.Name, 
OutcomeIndicator."Desc" AS OutcomeDesc, 
NewOutcomeIndicator.Description As NewOutcomeDesc 
FROM service 
FULL OUTER JOIN OutcomeIndicator ON ServiceOutcomeIndicator.OutcomeIndicatorID=OutcomeIndicator.OutcomeIndicatorID 
FULL OUTER JOIN NewOutcomeIndicator ON NewOutcomeIndicatorMapping.NewOutcomeIndicatorID=NewOutcomeIndicator.NewOutcomeIndicatorID 

然而,當我運行這個說法,它顯然返回的每一行,包括對服務名稱的多個值,因爲每個服務可以有多種結果/ NewOutcome配對。

+-------------+----------------+------------------+ 
| ServiceName | OutcomeDesc1 | NewOutcomeDesc1 | 
+-------------+----------------+------------------+ 
| Service34 | OutcomeDesc14 | NewOutcomeDesc14 | 
| Service34 | OutcomeDesc12 | NewOutcomeDesc12 | 
| Service35 | OutcomeDesc4 | NewOutcomeDesc4 | 
| Service44 | OutcomeDesc80 | NewOutcomeDesc80 | 
| Service44 | OutcomeDesc99 | NewOutcomeDesc99 | 
| Service51 | OutcomeDesc50 | NewOutcomeDesc50 | 

爲報告的目的,因爲這是被複制到Excel中,我希望更多的東西是這樣的:

+--------------+-----------------+-------------------+-----------------+-------------------+--------------+---------------------+ 
| ServiceName | OutcomeDesc1 | NewOutcomeDesc1 | OutcomeDesc2 | NewOutcomeDesc2 | OutcomeDesc3 | NewOutcomeDesc3 | 
+--------------+-----------------+-------------------+-----------------+-------------------+--------------+---------------------+ 
| Service34 | OutcomeDesc14 | NewOutcomeDesc14 | OutcomeDesc12 | NewOutcomeDesc12 |    |      | 
| Service35 | OutcomeDesc4 | NewOutcomeDesc4 |     |     |    |      | 
| Service44 | OutcomeDesc80 | NewOutcomeDesc80 | OutcomeDesc99 | NewOutcomeDesc99 |    |      | 
| Service51 | OutcomeDesc50 | NewOutcomeDesc50 |     |     |    |      | 
+--------------+-----------------+-------------------+-----------------+-------------------+--------------+---------------------+ 

如何,我可以改變我的SQL語句來做到這一點任何想法?我可以靜態定義列的數量,因爲我知道每個服務的結果不會超過3個。

我知道如何在sql中創建一個靜態數據透視表,但由於有數百個服務和結果,我無法定義統計分配每個服務值到列的邏輯。動態數據透視表對我而言也有點難以理解,但我還沒有找到一個能夠做到這一點的教程,同時還包括了一個聯合聲明。

任何幫助表示讚賞。

+0

,因爲你知道的列數事先不需要動態支點。當您根據表中的值創建列時,將使用動態數據透視表。 –

回答

1

你不需要爲這個充滿活力的支點,其實你甚至不需要使用真正的轉動命令時,你可以輕鬆地與CASE和GROUP BY模擬

檢索結果顯示,你在那裏後,只要使用ROW_NUMBER()函數爲每行分配數字1-3,最後使用該RN選擇進入哪個列的內容。

這是一段代碼,在第一個CTE中添加真實代碼。

WITH CTE_Source AS 
(
    --Your query goes here 
) 
, CTE_RN AS 
(
    SELECT * 
    , ROW_NUMBER() OVER (PARTITION BY ServiceName ORDER BY OutcomeDesc) RN 
    FROM CTE_Source 
) 
SELECT ServiceName 
, MAX(CASE WHEN RN = 1 THEN OutcomeDesc END) AS OutcomeDesc1 
, MAX(CASE WHEN RN = 1 THEN NewOutcomeDesc END) AS NewOutcomeDesc1 
, MAX(CASE WHEN RN = 2 THEN OutcomeDesc END) AS OutcomeDesc2 
, MAX(CASE WHEN RN = 2 THEN NewOutcomeDesc END) AS NewOutcomeDesc2 
, MAX(CASE WHEN RN = 3 THEN OutcomeDesc END) AS OutcomeDesc3 
, MAX(CASE WHEN RN = 3 THEN NewOutcomeDesc END) AS NewOutcomeDesc3 
FROM CTE_RN 
GROUP BY ServiceName 

DEMO using your data as SourceTable