串相当于总的来连接(string equivalent of Sum to concatenate)

2019-08-18 01:07发布

我想一个查询,输出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

Answer 1:

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
  • SQLFiddle演示

OUTPUT

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


Answer 2:

另一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

所有姓组由城市:

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

OUTPUT:

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


Answer 3:

SQL服务器(从2017)支持开箱即用的功能STRING_AGG

select p.id, STRING_AGG(pr.description, ',') as roles 
from person p 
inner join personrole pr ON p.id = pr.personid
inner join roles r ON r.id = pr.roleid
group by p.id


文章来源: string equivalent of Sum to concatenate