string equivalent of Sum to concatenate

2019-04-12 09:17发布

问题:

I would like a query to output on 1 line the Id from the left table and the descriptions from a joined table.

Schema:

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

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

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

Example data:

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

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

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

So, I'd like the output to be:

PersonId   Roles
1          user
2          user;administrator;tester

回答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 Demo

OUTPUT

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


回答2:

An other SQL example: using GROUP_CONCAT on a single table to group every first name client of a town.

script Sqlite :

Table:

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

Data:

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');

Normal select :

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

All prenom group by ville :

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

OUTPUT :

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


回答3:

SQL Server (starting with 2017) supports OOTB STRING_AGG function

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