sql server - How to get column values in one comma separated value -
i have table contains rows below
id user department 1 user1 admin 2 user1 accounts 3 user2 finance 4 user3 sales 5 user3 finance
i need select query results following format
id user department 1 user1 admin,accounts 2 user2 finance 3 user3 sales, finance
you tagged question both sql-server , plsql provide answers both sql server , oracle.
in sql server can use for xml path
concatenate multiple rows together:
select distinct t.[user], stuff((select distinct ', ' + t1.department yourtable t1 t.[user] = t1.[user] xml path(''), type ).value('.', 'nvarchar(max)') ,1,2,'') department yourtable t;
see sql fiddle demo.
in oracle 11g+ can use listagg
:
select "user", listagg(department, ',') within group (order "user") departments yourtable group "user"
see sql fiddle demo
prior oracle 11g, use wm_concat
function:
select "user", wm_concat(department) departments yourtable group "user"
Comments
Post a Comment