Search code examples
sqlsql-servert-sqljoinfor-xml-path

Concatenate two columns and join by ID


and thanks in advance! I'm looking for the most efficient way to concatenate each "Secretary" where JobTitle = "Assistant" and then join to another table by "Empl_code". This will be done in a view.

declare @Atty_Sec table
(    Empl_Code int,
    Attorney varchar(20),
    Secretary varchar(50),
    SecJobTitle varchar(50)
)
insert into @Atty_Sec
select 1,'John Smith','Mary Anne', 'Assistant' union all
select 1,'John Smith', 'Joanne Rockit','Office Manager'union all
select 1,'John Smith', 'Sharon Osbourne','Assistant'union all
select 2,'Steve Jobs', 'Katherine Kay','Assistant' union all
select 2,'Steve Jobs','Rylee Robot','Office Manager' union all
select 3,'Mike Michaels','Joe Joseph','Assistant' union all
select 3,'Mike Michaels','Ronald McDonald','Office Manager'

Select * from @Atty_Sec

Join against this table:

declare @UserTable table
(
    Empl_Code int,
    Attorney varchar(20)

)
insert into @UserTable
select 1,'John Smith' union all
select 2,'Steve Jobs'union all
select 3,'Mike Michaels'

Select * from @UserTable 

The output of the view should look Like this with two columns "Empl_Code" and one called [Assistants]:

  • 1 Mary Anne; Sharon Osbourne
  • 2 Katherine Kay
  • 3 Joe Joseph

Solution

  • You can use group by and stuff as below:

    select a.empl_code, stuff((select ','+ secretary from @atty_Sec where empl_Code = a.empl_Code and SecJobTitle = 'Assistant' for xml path('')),1,1,'')
      from @Atty_Sec a
    group by a.Empl_Code