2014-07-14 62 views
0

我有一個表包含了所有的名與不同的類,像這樣:選擇列,它們各具地方條件SQL

Name Class 

Jack A 

Nick B 

Simon C 

David B 

Linda B 

Alice C 

現在我希望得到一個表格,以A級,B,C作爲列,其中包含其尊重類內的名稱:

A----------B----------C 

Jack------Nick-------Simon 

----------David------Alice 

----------Linda----------- 

如何在SQL查詢中獲得此類表?對不起格式不好,不知道如何在SO中創建表格。

+0

您需要一個數據透視表。如果你不知道有多少類,你將會使用動態數據透視表。所以http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/ –

回答

3

這是一種使用聚合的方法。這可能是最簡單的方法:

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); 
+0

不錯。我想出了一個類似的FULL JOIN解決方案。使用聚合不會發生在我身上,但它可能會更好。 –

+0

感謝您的幫助!只是想知道,如果表中包含大量的數據,哪種方式會更快? – SSilicon

+0

@SSilicon。 。 。這真的取決於。 SQL Server對於聚合非常好。你會想要'class,name'上的索引。嘗試兩種方式,看看會發生什麼。 –

1

你問的數據是不是真的很關係,在這種情況下,你通常會從做取得更好的成績在客戶端應用程序中工作。但是,這往往是不可能的:

SELECT A.Name as A, B.Name as B, C.Name AS C 
FROM 
    (select Name, row_number over (order by name) as ordinal from table where class = 'A') A 
FULL JOIN 
    (select Name, row_number over (order by name) as ordinal from table where class = 'B') B 
    ON B.ordinal = A.ordinal 
FULL JOIN 
    (select Name, row_number over (order by name) as ordinal from table where class = 'C') C 
    ON C.ordinal = coalesce(A.ordinal, B.ordinal)