连接两列并按ID加入

时间:2016-10-24 20:30:46

标签: sql sql-server tsql join for-xml-path

并提前致谢!我正在寻找最有效的方法来连接JobTitle =“Assistant”的每个“秘书”,然后通过“Empl_code”加入另一个表。这将在视图中完成。

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

加入此表:

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]:

  • 1玛丽安妮; Sharon Osbourne
  • 2 Katherine Kay
  • 3 Joe Joseph

2 个答案:

答案 0 :(得分:2)

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

返回

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

答案 1 :(得分:0)

您可以使用group by和stuff:

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