2014-01-16 85 views
1

對不起,我是新來的SQL,所以我在想,如果有人可以幫助我有以下:SQL Server 2008中樞軸和的毗連

我有一個表

+--------+----------+ 
|Position|PlayerName| 
+--------+----------+ 
|Forward |Tom  | 
+--------+----------+ 
|Forward |John  | 
+--------+----------+ 
|Center |Dave  | 
+--------+----------+ 
|Defense |Harry  | 
+--------+----------+ 
|Center |Bob  | 
+--------+----------+ 
|Defense |James  | 
+--------+----------+ 
|Goalie |Mike  | 
+--------+----------+ 
|Goalie |Tim  | 
+--------+----------+ 

結果

+---------+---------+------------+---------+ 
|Forward |Center |Defense  |Goalie | 
+---------+---------+------------+---------+ 
|Tom, John|Dave, Bob|Harry, James|Mike, Tim| 
+---------+---------+------------+---------+ 
+4

你有沒有試着編寫一個查詢來做到這一點?你應該真的展示你解決這個問題的嘗試。 – Taryn

+0

這不僅僅是一個關鍵點,你還將連接這些可能的行。 –

+0

嘗試使用sqlfiddle.com作爲這個例子 - 它會幫助你和那些試圖幫助你的人。 – eebbesen

回答

2

爲了獲得結果,您必須分兩步完成。首先,您需要連接Position的所有PlayerNames。一旦你有了列表,那麼你可以將數據從行轉移到列中。

由於您使用的是SQL Server,因此有幾種不同的方法可以連接數據。您可以使用STUFFFOR XML PATH

select t1.position, 
    STUFF(
     (SELECT ', ' + t2.PlayerName 
     FROM yourtable t2 
     where t1.position = t2.position 
     FOR XML PATH ('')) 
     , 1, 1, '') AS PlayerName 
from yourtable t1 

SQL Fiddle with Demo。這得到你的數據到結果:

| POSITION | PLAYERNAME | 
|----------|---------------| 
| Forward |  Tom, John | 
| Center |  Dave, Bob | 
| Defense | Harry, James | 

現在,您的數據已經被連接起來,那麼你可以將數據通過聚合函數CASE表達式轉換,也可以使用PIVOT。

骨料與CASE

;with cte as 
(
    select t1.position, 
    STUFF(
     (SELECT ', ' + t2.PlayerName 
      FROM yourtable t2 
      where t1.position = t2.position 
      FOR XML PATH ('')) 
      , 1, 1, '') AS PlayerNames 
    from yourtable t1 
) 
select 
    max(case when position = 'Forward' then PlayerNames end) Forward, 
    max(case when position = 'Center' then PlayerNames end) Center, 
    max(case when position = 'Defense' then PlayerNames end) Defense, 
    max(case when position = 'Goalie' then PlayerNames end) Goalie 
from cte 

SQL Fiddle with Demo

PIVOT

;with cte as 
(
    select t1.position, 
    STUFF(
     (SELECT ', ' + t2.PlayerName 
      FROM yourtable t2 
      where t1.position = t2.position 
      FOR XML PATH ('')) 
      , 1, 1, '') AS PlayerName 
    from yourtable t1 
) 
select Forward, Center, Defense, Goalie 
from cte 
pivot 
(
    max(playername) 
    for position in (Forward, Center, Defense, Goalie) 
) piv; 

SQL Fiddle with Demo

均可以得到一個結果:

| FORWARD |  CENTER |  DEFENSE |  GOALIE | 
|------------|------------|---------------|------------| 
| Tom, John | Dave, Bob | Harry, James | Mike, Tim | 
+0

感謝bluefeet,我現在正在閱讀這些東西的功能,謝謝你讓我知道。我從來沒有見過它。再次感謝您的幫助。我現在也設置了一個SQL Fiddle帳戶。謝謝。 –