如何连续返回多列结果

时间:2013-03-25 06:39:46

标签: sql-server sql-server-2008

我在数据库中有2个表。

T1

ID    TeamLeader
---   -----------
1     Iron Man
2     Thor
3     Hulk

T2

TeamID   Member
------   ------
1        Superman
1        Spiderman
2        Batman
2        Catwomen
2        Robin
3        Black Widow
3        Hawk Eye
3        Captain America

我希望返回一个SELECT语句,如下所示。

TeamID  TeamLeader  Member
------  ----------  ------
1       Iron Man    Superman;Spiderman;
2       Thor        Batman;Catwomen;Robin;
3       Hulk        Black Widow; Hawk Eye;Captain America;

我尝试创建一个使用临时表的函数,但它说我不能在函数中使用临时表。

请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以使用FOR XMLSTUFF来执行此操作。类似的东西:

SELECT 
  t1.id,
  t1.teamleader,
  STUFF((
    SELECT '; ' + t2.member  
    FROM t2
    WHERE t2.teamId = t1.id
    FOR XML PATH (''))
  ,1,2,'') AS Members
FROM t1
GROUP BY t1.Id, 
         t1.teamLeader;

SQL Fiddle Demo

这会给你:

| ID | TEAMLEADER |                                MEMBERS |
------------------------------------------------------------
|  1 |   Iron Man |                    Superman; Spiderman |
|  2 |       Thor |                Batman; Catwomen; Robin |
|  3 |       Hulk | Black Widow; Hawk Eye; Captain America |

答案 1 :(得分:0)

SELECT
     ID, TeamLeader,
     STUFF(
         (SELECT ';' + [Member]
          FROM Table2
          WHERE TeamID = a.ID
          FOR XML PATH (''))
          , 1, 1, '')  AS MembersList
FROM Table1 AS a
GROUP BY ID, TeamLeader

输出

╔════╦════════════╦══════════════════════════════════════╗
║ ID ║ TEAMLEADER ║             MEMBERSLIST              ║
╠════╬════════════╬══════════════════════════════════════╣
║  1 ║ Iron Man   ║ Superman;Spiderman                   ║
║  2 ║ Thor       ║ Batman;Catwomen;Robin                ║
║  3 ║ Hulk       ║ Black Widow;Hawk Eye;Captain America ║
╚════╩════════════╩══════════════════════════════════════╝

输出

╔════╦════════════╦═════════════════════════════════════════╗
║ ID ║ TEAMLEADER ║               MEMBERSLIST               ║
╠════╬════════════╬═════════════════════════════════════════╣
║  1 ║ Iron Man   ║ Superman; Spiderman;                    ║
║  2 ║ Thor       ║ Batman; Catwomen; Robin;                ║
║  3 ║ Hulk       ║ Black Widow; Hawk Eye; Captain America; ║
╚════╩════════════╩═════════════════════════════════════════╝