2014-05-13 2 views
0

이것은 현재 나의 테이블입니다. 내가 피벗을 시도했지만이 NVARCHAR이기 때문에 내가 전화 번호에 집계 함수를 사용할 수 없기 때문에 할 수없는피벗을 사용하여 행을 열로 변환

Name Cellular Workphone Homephone 
a 303-333-3333 444-444-4444 222-222-2222 
b 222-222-2222   
c 111-111-1111 333-333-3333 888-888-8888 
d 999-999-9999 777-777-7777 111-222-3333 

:

Name PhoneType Number 
a Cellular 303-333-3333 
a WorkPHone 444-444-4444 
b Workphone 222-222-2222 
c Cellular 111-111-1111 
c WorkPHone 333-333-3333 
c HomePhone 888-888-8888 
d Cellular 999-999-9999 
d WorkPHone 777-777-7777 
d HomePhone 111-222-3333 

나는로 변환 할. 어떻게 변환 할 수 있습니까?

답변

0

다음과 같이 select query를 사용하여 alternate to pivot을 사용할 수 있습니다.

with xx as(
select 'a' namee,'cellular' typee,'303-333-3333' numberr from dual union all 
select 'a' namee,'WorkPHone' typee,'444-444-4444' numberr from dual union all 
select 'b' namee,'WorkPHone' typee,'222-222-2222' numberr from dual union all 
select 'c' namee,'cellular' typee,'111-111-1111' numberr from dual union all 
select 'c' namee,'WorkPHone' typee,'333-333-3333' numberr from dual union all 
select 'c' namee,'HomePhone' typee,'888-888-8888' numberr from dual 
) 
select 
x.namee, 
max(case when x.typee='cellular' then x.numberr else '' end) as CELLULAR, 
max(case when x.typee='WorkPHone' then x.numberr else '' end) as WORKPHONE, 
max(case when x.typee='HomePhone' then x.numberr else '' end) as HOMEPHONE 
from xx x 
group by x.namee 
order by x.namee; 

편집 :

XX 테이블은 테이블 이름으로 교체해야합니다. 테이블의 이름이 my_table 인 것으로 가정하면 최종 쿼리는 다음과 같습니다.

select x.Name , 
max(case when x.PhoneType='cellular' then x.Number else '' end) as CELLULAR, 
max(case when x.PhoneType='WorkPHone' then x.Number else '' end) as WORKPHONE, 
max(case when x.PhoneType='HomePhone' then x.Number else '' end) as HOMEPHONE 
from 
my_table x 
group by x.Name 
order by x.Name; 
+0

6 개의 행이 있지만 100K 개의 행이있는 경우이 데이터는 사용할 수 없습니다. 맞습니까? – NDuwal

+0

xx 테이블을 테이블 이름으로 바꿔야합니다. 귀하의 테이블에 my_table이라는 이름의 쿼리가 있다고 가정합니다. select x.Name, max (대소 문자가 x.PhoneType = 'cellular'이고 x.Number else ''end)가 CELLULAR 일 때 max .PhoneType = 'WorkPhone'then x.Number else ''end) as work 전화 번호 최대 (x.PhoneType = 'HomePhone'일 때 x.Number else ''끝)을 집으로 사용 부터 xx x 그룹 x. x.Name별로 이름; –

+0

@NDuwal : 답변이 수정되었습니다. 나는 이것이 더 많은 수의 행에 문제를 일으킬 것이라고 생각하지 않는다. With 절은 단지 더미 테스트 데이터 일뿐입니다. 귀하의 환경에서 동일한 것을 확인하고 저희에게 알려주십시오. –