-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 XMLwithを使用しSTUFFてこれを行うことができます。何かのようなもの:

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 に答える