爲了獲得結果,您必須分兩步完成。首先,您需要連接Position
的所有PlayerNames
。一旦你有了列表,那麼你可以將數據從行轉移到列中。
由於您使用的是SQL Server,因此有幾種不同的方法可以連接數據。您可以使用STUFF
和FOR 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 |
你有沒有試着編寫一個查詢來做到這一點?你應該真的展示你解決這個問題的嘗試。 – Taryn
這不僅僅是一個關鍵點,你還將連接這些可能的行。 –
嘗試使用sqlfiddle.com作爲這個例子 - 它會幫助你和那些試圖幫助你的人。 – eebbesen