简体   繁体   English

连接两列并按ID连接

[英]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". 我正在寻找最有效的方法来连接每个“秘书”,其中JobTitle =“ Assistant”,然后通过“ 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]: 视图的输出应看起来像这样,其中有两列“ Empl_Code”,其中一列称为[Assistants]:

  • 1 Mary Anne; 1玛丽·安妮; Sharon Osbourne 莎朗·奥斯本
  • 2 Katherine Kay 2凯瑟琳·凯
  • 3 Joe Joseph 3乔·约瑟夫
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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