2016-10-10 145 views
1

我有一個表,如下所示:SQL數據透視表分組

Date  Ticket Question Response 
2016-10-01 1  Score?  10 
2016-10-01 1  Reason?  Awesome 
2016-10-02 2  Score?  9 
2016-10-02 2  Reason?  Good 
2016-10-03 3  Score?  8 
2016-10-03 3  Reason?  Okay 

我要來透視在SQL爲:

Date  Ticket Score? Reason? 
2016-10-01 1  10  Awesome 
2016-10-02 2  9  Good 
2016-10-03 3  8  Okay 

是否有人可以幫忙嗎?如果需要,我很樂意提供更多細節。

enter image description here

回答

1

如果不需要通過動態的,一個簡單的條件匯聚應該做的。

Select Date 
     ,Ticket 
     ,Score = max(case when Question='Score?' then Response else null end) 
     ,Reason = max(case when Question='Reason?' then Response else null end) 
From YourTable 
Group By Date,Ticket 
-1
SELECT Date, 
     Ticket, 
     MAX(CASE WHEN Question = 'Score?' THEN Response END   
      ) AS Score?, 
     MAX(CASE WHEN Question = 'Reason' THEN Response END   
      ) AS Reason?, 
    FROM table 
GROUP BY Date,Ticket 
; 
0

嘗試以下使用PIVOT:

Select * from 
(Select * from table) x 
PIVOT 
(
    MAX(Response) FOR Question IN ([Score?], [Reason?]) 
) p