我想要一个查询在 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
最佳答案
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 ║
╚══════════╩════════════════════════════╝
关于sql - 要连接的 Sum 的等效字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15633373/