2017-05-23 1 views
0

2 개의 테이블을 1 개의 열에 병합하려고합니다. 어쨌든 내가 할 수 있니?2 테이블을 1 줄로 병합하는 방법이 있습니까

unit Item 
1 apple 
2 ball 
3 cat 
4 dog 
5 elephant 

표 2 :

unit Field1 
1 test1 
1 test2 
2 apple1 
2 test1 
3 ball1 
3 cat1 
4 dot1 
4 elp 
5 rat 
5 rat1 
5 rat2 

내가 사용하는 경우 :

Select * from table1 as a left join table2 as b on a.unit = b.unit, 

예를 들어

, 나는 표 1 및

표처럼 보이는 표 2는이 나는 여러 행을 t 여기에 테이블의 여러 단위가 2

내가 원하는

Unit item field1_1 field1_2 field1_3 
1 apple test1 test2  null 
2 ball apple1 test1  nul 
3 cat ................... 
4 dog.............. 
5 elephant rat rat1 rat2 

내가 결과를 얻을 수 있습니다 어쨌든 있나요입니까?

+0

단위 당 최대 필드 수는 몇 개입니까? – GurV

+0

9 개의 필드가 있습니다 – Sam

+1

가능한 [SQL Server 동적 PIVOT 쿼리?] (https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) –

답변

1

당신은

select unit, 
    item, 
    max(case when seqnum = 1 then field end) as field1, 
    max(case when seqnum = 2 then field end) as field2, 
    . . . 
    max(case when seqnum = 9 then field end) as field9 
from (
    select t1.unit, 
     t1.item, 
     t2.field, 
     row_number() over (
      partition by t1.unit order by t2.field 
      ) as seqnum 
    from table1 t1 
    join table2 t2 on t1.unit = t2.unit 
    ) t 
group by unit, 
    item; 
+0

감사합니다. 이것이 제가 찾고 있던 것입니다. – Sam

0

시도가 사용하는 각 단위 내에서 일련 번호를 생성하고 데이터를 피벗 조건부 집계를 사용하는 ROW_NUMBER를 사용할 수 있습니다 감사 GROUP_CONCAT(Feild1) :

Select a.unit , a.item , GROUP_CONCAT(Feild1) as feild1 from table1 as a left join table2 as b on a.unit = b.unit group by a.unit , a.item 

결과 :

Unit Item  Feild1 
1   apple  Test1,test2 
........... .... 
관련 문제