提前谢谢!我正在寻找最有效的方法将每个“秘书”连接起来,其中JobTitle =“助手”,然后通过"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“,另一列为助手:
发布于 2016-10-24 20:46:08
您可以按以下方式使用group by和group:
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发布于 2016-10-24 20:36:33
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 Josephhttps://stackoverflow.com/questions/40227017
复制相似问题