2016-10-10 141 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