连接两列并按 ID 连接

Concatenate two columns and join by ID

提前致谢!我正在寻找最有效的方法来连接每个 "Secretary",其中 JobTitle = "Assistant",然后通过 "Empl_code" 连接到另一个 table。这将在视图中完成。

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

加入反对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 

视图的输出应该看起来像这样,有两列 "Empl_Code" 和一个名为 [Assistants] 的列:

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

您可以使用分组依据和如下内容:

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