Social Icons

Pages

Sunday, March 15, 2015

How to display row values in columns

Here I am going to return a result set that has one record per company and a column that has a listing of employee name for each company separated by semicolons.

Below is the table output which I used to query the data.


MS Sql
Select distinct company,employees from tbl_employee as e OUTER APPLY
(SELECT STUFF(( SELECT ';' + emp.name FROM tbl_employee AS emp
where emp.company=e.company
FOR XML PATH('') ), 1,1,'') AS employees ) AS r
PostgreSQL
 select company, array_to_string(array_agg(name), ',')  from tbl_employee group  by company
Output:

Reference:
http://www.postgresonline.com/journal/archives/191-String-Aggregation-in-PostgreSQL,-SQL-Server,-and-MySQL.html  

No comments:

Post a Comment