为了获得结果,您必须分两步完成。首先,您需要连接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