SQL数据透视表分组

时间:2016-10-10 15:38:09

标签: sql sql-server group-by pivot

我有一张表格如下:

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

3 个答案:

答案 0 :(得分: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 :(得分:0)

使用PIVOT尝试以下:

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

答案 2 :(得分:-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 
;