8

我想要一个查询以在 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
4

3 回答 3

12
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

输出

╔══════════╦════════════════════════════╗
║ PERSONID ║      DESCRIPTIONLIST       ║
╠══════════╬════════════════════════════╣
║        1 ║ user                       ║
║        2 ║ user;admininstrator;tester ║
╚══════════╩════════════════════════════╝
于 2013-03-26T09:29:39.600 回答
8

SQL Server(从 2017 开始)支持 OOTB 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
于 2019-03-19T09:11:49.167 回答
0

另一个 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';

输出 :

prenom   age  ville

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

ville 的所有 prenom 组:

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

输出 :

ville      liste
--------   ---------
Nice       Lili
Paris      Clarisse,Madeleine,Victoire
Toulouse   Anthony,Jacques,Henry 
于 2015-01-15T21:11:08.993 回答