Query for comma-separated ids to comma-separated values

后端 未结 5 1558
终归单人心
终归单人心 2021-01-03 03:16

I have 2 tables

Departments

ID  Dept
---------
1   HR
2   Accts
3   IT

Employee

I         


        
5条回答
  •  温柔的废话
    2021-01-03 03:30

    You can also use a recursive CTE to split the data and then use FOR XML PATH to concatenate the rows into a single row:

    ;with cte (id, name, deptid, depts) as
    (
      select id, name,
        cast(left(depts, charindex(',',depts+',')-1) as varchar(50)) deptid,
             stuff(depts, 1, charindex(',',depts+','), '') depts
      from employee
      union all
      select id, name,
        cast(left(depts, charindex(',',depts+',')-1) as varchar(50)) deptid,
        stuff(depts, 1, charindex(',',depts+','), '') depts
      from cte
      where depts > ''
    ) 
    select e.id, e.name,
      stuff((
             select distinct ', '+ d.dept
             from cte c
             inner join departments d
                on c.deptid = d.id
             where e.id = c.id
             for XML path('')),1,1,'') Depts
    from employee e
    

    See SQL Fiddle with Demo

    Result:

    | ID |     NAME |          DEPTS |
    ----------------------------------
    |  1 |    Kevin |      Accts, HR |
    |  2 | Michelle |             HR |
    |  3 |     Troy |         HR, IT |
    |  4 |   Rheesa |  Accts, HR, IT |
    

提交回复
热议问题