字符串相当于Sum以连接

时间:2013-03-26 09:24:21

标签: sql sql-server sql-server-2008 tsql

我想查询一行输出左表中的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

3 个答案:

答案 0 :(得分:11)

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 ║
╚══════════╩════════════════════════════╝

答案 1 :(得分: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

所有prenom group by ville:

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

输出:

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

答案 2 :(得分:0)

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