Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string equivalent of Sum to concatenate

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
like image 289
Stu Harper Avatar asked Mar 26 '13 09:03

Stu Harper


People also ask

Can you use += to concatenate strings?

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 .

How do you concatenate text and sum in Excel?

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.

What can I use instead of 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).

Can you use concatenate in sum if?

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.


2 Answers

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 ║
╚══════════╩════════════════════════════╝
like image 75
John Woo Avatar answered Sep 17 '22 15:09

John Woo


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
like image 30
Hodza Avatar answered Sep 21 '22 15:09

Hodza