這是一種使用聚合的方法。這可能是最簡單的方法:
select max(case when class = 'a' then name end) as a,
max(case when class = 'b' then name end) as b,
max(case when class = 'c' then name end) as c
from (select name, class, row_number() over (partition by class order by (select NULL)) as seqnum
from nameclasses
) nc
group by seqnum
order by seqnum;
這是我張貼的原始方法。它不使用聚合,但它確實有很多的連接:
select a.name as a, b.name as b, c.name as c
from (select name, row_number() over (order by (select NULL)) as seqnum
from nameclasses nc
where class = 'A'
) a full outer join
(select name, row_number() over (order by (select NULL)) as seqnum
from nameclasses nc
where class = 'B'
) b
on a.seqnum = b.seqnum full outer join
(select name, row_number() over (order by (select NULL)) as seqnum
from nameclasses nc
where class = 'c'
) c
on c.seqnum = coalesce(a.seqnum, b.seqnum)
order by coalesce(a.seqnum, b.seqnum, c.seqnum);
您需要一個數據透視表。如果你不知道有多少類,你將會使用動態數據透視表。所以http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ –