2014-01-16 84 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帐户。谢谢。 –