drop table student
create Table student (name varchar(25),continent varchar(25));
insert into student values('Jack','America')
insert into student values('Pascal','Europe')
insert into student values('Xi','Asia')
insert into student values('Jane','America')
A U.S graduate school has students from Asia, Europe and America. The students' location information are stored in table student
as below.
| name | continent | |--------|-----------| | Jack | America | | Pascal | Europe | | Xi | Asia | | Jane | America |
Pivot the continent column in this table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia and Europe respectively. It is guaranteed that the student number from America is no less than either Asia or Europe.
For the sample input, the output is:
| America | Asia | Europe | |---------|------|--------| | Jack | Xi | Pascal | | Jane | | |
SELECT
America,
Asia,
Europe
FROM
(SELECT
row_number() OVER (PARTITION BY continent order by name) AS asid,
name AS Asia
FROM
student
WHERE
continent = 'Asia'
) AS t1
RIGHT JOIN
(SELECT
row_number()
OVER (PARTITION BY continent order by name) AS amid,
name AS America
FROM
student
WHERE
continent = 'America'
) AS t2 ON asid = amid
LEFT JOIN
(SELECT
row_number()
OVER (PARTITION BY continent order by name) AS euid,
name AS Europe
FROM
student
WHERE
continent = 'Europe'
) AS t3 ON amid = euid;
declare @as int
declare @am int
declare @eu int
set @as=0;
set @am=0;
set @eu=0;
SELECT
[America], [Asia], [Europe]
FROM
(SELECT
@as + 1 AS asid, name AS Asia
FROM
student
WHERE
continent = 'Asia'
) AS t1
RIGHT JOIN
(SELECT
@am + 1 AS amid, name AS America
FROM
student
WHERE
continent = 'America'
) AS t2 ON asid = amid
LEFT JOIN
(SELECT
@eu + 1 AS euid, name AS Europe
FROM
student
WHERE
continent = 'Europe'
) AS t3 ON amid = euid
select
(case when continent = 'America' then name else '' end) America,
(case when continent = 'Europe' then name else '' end) Europe,
(case when continent = 'Asia' then name else '' end) Asia
from student
select [America],[Europe],[Asia]
from (select name,continent from student) as D
pivot(min(name) for continent in ([America],[Europe],[Asia]) ) as P