2016-10-24 4 views
1

으로 가입하고 미리 감사드립니다! JobTitle = "Assistant"인 각 "Secretary"를 연결 한 다음 "Empl_code"로 다른 테이블에 조인하는 가장 효율적인 방법을 찾고 있습니다. 이 작업은보기에서 수행됩니다. 두 개의 열을 연결하고 ID :

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 

이 테이블에 대해 가입 :

  • 1 메리 앤 :

    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"를 선택하고 [보조]라는 하나 같이한다 ; 샤론 오스본

  • 2 캐서린 케이
  • 3 조 조셉

답변

0
당신은에 의해 그룹을 사용할 수 있습니다

아래와 같이 재료 :

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 
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 
관련 문제