SQL数据透视表

时间:2017-06-25 16:45:52

标签: mysql sql

enter image description here

请参阅上图中我的SQL问题。

如何为此编写SQL?

1 个答案:

答案 0 :(得分:3)

DECLARE @Columns nvarchar(MAX),@SQL nvarchar(MAX);
SET @Columns=N'';
SELECT @Columns+=IIF(@Columns='', 
QUOTENAME(continent),N','+QUOTENAME(continent))
from(Select continent from student group by continent ) as x ;
Set @SQL=N'SELECT ['+STUFF(@Columns,1,1,'')+'
FROM ( Select  continent,name,row_number() over(partition by continent order 
by name) rn from student ) AS j
PIVOT( MAX( name) FOR continent IN ( ['+STUFF(@Columns,1,1,'')+')) as p';
EXECUTE  sp_executesql @SQL;