2013-03-26 89 views
3

我想要一個查詢輸出1行左側表中的Id和來自連接表的描述。字符串當量的總和連接

架構:

person 
---------  
id (int) 

role 
------------- 
id (int) 
description (varchar(100)) 

personrole 
------------- 
personid (int) 
roleid (int) 

實施例的數據:

person 
------------ 
id 
1 
2 

role 
------------ 
id description 
1 user 
2 admininstrator 
3 tester 

personrole 
------------- 
personid roleid 
1   1 
2   1 
2   2 
2   3 

所以,希望我的輸出爲:

PersonId Roles 
1   user 
2   user;administrator;tester 

回答

10
SELECT 
    p.ID PersonID, 
    STUFF(
     (SELECT ';' + b.description 
      FROM personrole a 
       INNER JOIN role b 
        ON a.roleid = b.id 
      WHERE a.personid = p.id 
      FOR XML PATH ('')) 
      , 1, 1, '') AS DescriptionList 
FROM person AS p 
GROUP BY p.ID 

OUTPUT

╔══════════╦════════════════════════════╗ 
║ PERSONID ║  DESCRIPTIONLIST  ║ 
╠══════════╬════════════════════════════╣ 
║  1 ║ user      ║ 
║  2 ║ user;admininstrator;tester ║ 
╚══════════╩════════════════════════════╝ 
+0

感謝您的。作品一種享受。 – 2013-03-26 10:09:18

+0

+1爲SQLFiddle鏈接,之前不知道該服務。 – Touko 2013-10-29 10:03:52

1

一個其他SQL例如:使用GROUP_CONCAT上單個表組的一個小鎮的每個名字的客戶端。

腳本SQLite的:

表:

CREATE TABLE IF NOT EXISTS 'user'(
     prenom STRING, 
     age INTEGER, 
     ville STRING); 

數據:

INSERT INTO 'user' ('prenom', 'age', 'ville') VALUES 
     ('Anthony', 20, 'Toulouse'), 
     ('Clarisse', 18, 'Paris'), 
     ('Madeleine', 58, 'Paris'), 
     ('Jacques', 45, 'Toulouse'), 
     ('Henry', 26, 'Toulouse'), 
     ('Lili', 14, 'Nice'), 
     ('Victoire', 38, 'Paris'); 

正常選擇:

SELECT * FROM 'user'; 

OUTPUT:

prenom age ville 

-------- -- --------- 
Anthony 20 Toulouse 
Clarisse 18 Paris 
Madeleine 58 Paris 
Jacques 45 Toulouse 
Henry  26 Toulouse 
Lili  14 Nice 
Victoire 38 Paris 

所有prenom組由威樂:

SELECT ville, GROUP_CONCAT(prenom, ',') FROM user GROUP BY ville;

OUTPUT:

ville  liste 
-------- --------- 
Nice  Lili 
Paris  Clarisse,Madeleine,Victoire 
Toulouse Anthony,Jacques,Henry 
+0

對於像我這樣的人,只是一個說明這是一個MySQL的答案,但問題是MS SQL Server。 – Paul 2015-12-21 10:33:35