简体   繁体   中英

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
Select A.Empl_Code
      ,Assistants = B.Value
 From (Select Distinct Empl_Code From @Atty_Sec) A
 Cross Apply (Select Value=Stuff((Select Distinct ',' + Secretary 
                      From  @Atty_Sec 
                      Where Empl_Code=A.Empl_Code 
                        and SecJobTitle ='Assistant'
                      For XML Path ('')),1,1,'') 

             ) B

Returns

Empl_Code   Assistants 
1           Mary Anne,Sharon Osbourne
2           Katherine Kay
3           Joe Joseph

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM