SQL 透视 Table 分组
SQL Pivot Table Grouping
我有一个table如下:
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
有人可以帮忙吗?如果需要,我很乐意提供更多详细信息。
如果不需要动态,一个简单的条件聚合就可以了。
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
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
;
使用 PIVOT 尝试以下操作:
Select * from
(Select * from table) x
PIVOT
(
MAX(Response) FOR Question IN ([Score?], [Reason?])
) p
我有一个table如下:
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
有人可以帮忙吗?如果需要,我很乐意提供更多详细信息。
如果不需要动态,一个简单的条件聚合就可以了。
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
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
;
使用 PIVOT 尝试以下操作:
Select * from
(Select * from table) x
PIVOT
(
MAX(Response) FOR Question IN ([Score?], [Reason?])
) p