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
The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .
Select a cell where you want to enter the formula. Type =CONCATENATE( in that cell or in the formula bar. Press and hold Ctrl and click on each cell you want to concatenate.
Use the ampersand & character instead of the CONCATENATE function. The ampersand (&) calculation operator lets you join text items without having to use a function. For example, =A1 & B1 returns the same value as =CONCATENATE(A1,B1).
Because the CONCATENATE function accepts additional functions as arguments, we don't need auxiliary cells and can integrate the SUMIF function directly into the formula.
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
OUTPUT
╔══════════╦════════════════════════════╗
║ PERSONID ║ DESCRIPTIONLIST ║
╠══════════╬════════════════════════════╣
║ 1 ║ user ║
║ 2 ║ user;admininstrator;tester ║
╚══════════╩════════════════════════════╝
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With