-2

我在数据库中有 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;

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

请帮忙。

4

2 回答 2

1

您可以使用FOR XMLwithSTUFF来执行此操作。就像是:

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 小提琴演示

这会给你:

| ID | TEAMLEADER |                                MEMBERS |
------------------------------------------------------------
|  1 |   Iron Man |                    Superman; Spiderman |
|  2 |       Thor |                Batman; Catwomen; Robin |
|  3 |       Hulk | Black Widow; Hawk Eye; Captain America |
于 2013-03-25T06:42:32.600 回答
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; ║
╚════╩════════════╩═════════════════════════════════════════╝
于 2013-03-25T06:43:45.673 回答