2015-01-29 2 views
1

피봇 팅 및 트랜스 포스 데이터에 관한 많은 게시물과 주제를 보았습니다. 필자는 이해하지 못하거나 내가해야 할 일을 복잡하게하려고 노력 중입니다.행에 저장된 피벗/트랜스 포즈 전화 번호

SELECT Customer, Telephone 
FROM DetailsTable 
WHERE Customer = 74270571 
GROUP BY Customer, Telephone 

이 반환 : 내가 지금 같은 간단한 select 문을 실행하는거야

Customer | Telephone 
74270571 | 01556589962 
74270571 | 07756563729 

그리고 내가 무엇을 얻기 위해 노력하고 있어요 것은을

Customer | Tel1   | Tel2 
74270571 | 01556589962 | 07756563729 

가있을 수 있습니다 최대 5 개의 전화 번호. 각 Customer에 대해 여러 Telephone 값을 가지고 있기 때문에

답변

1

는 결과를 얻을 수있는 가장 쉬운 방법은 각 Telephone/Customer 조합에 대해 고유 한 값을 생성 row_number 같은 윈도우 기능을 사용하는 것입니다. 이 값을 얻으면 집계 함수와 CASE 식 또는 PIVOT 함수를 사용하여 결과를 PIVOT 수 있습니다.

최대 5 개의 전화 번호가 있으므로이 코드를 하드 코딩 된 버전이나 정적 버전으로 쉽게 작성할 수 있습니다. CASE 표현식으로 집계 함수를 사용하여 코드가 될 것이다 : 당신은 PIVOT 기능을 사용하려면

select 
    customer, 
    Tel1 = max(case when rn = 1 then telephone else null end), 
    Tel2 = max(case when rn = 2 then telephone else null end), 
    Tel3 = max(case when rn = 3 then telephone else null end), 
    Tel4 = max(case when rn = 4 then telephone else null end), 
    Tel5 = max(case when rn = 5 then telephone else null end) 
from 
(
    select customer, telephone, 
    rn = row_number() over(partition by customer order by telephone) 
    from DetailsTable 
) x 
group by customer; 

SQL Fiddle with Demo

를 참조하십시오, 다음 코드는 다음과 같습니다

select customer, 
    Tel1, 
    Tel2, 
    Tel3, 
    Tel4, 
    Tel4 
from 
(
    select customer, telephone, 
    col = 'Tel'+cast(row_number() over(partition by customer order by telephone) 
        as varchar(1)) 
    from DetailsTable 
) x 
pivot 
(
    max(telephone) 
    for col in (Tel1, Tel2, Tel3, Tel4, Tel5) 
) p 

SQL Fiddle with Demo를 참조하십시오 . 둘 다 결과를 얻습니다 :

| CUSTOMER |  TEL1 |  TEL2 | TEL3 | TEL4 | 
|----------|------------|------------|--------|--------| 
| 74270571 | 1556589962 | 7756563729 | (null) | (null) | 
+0

나는이 장소를 언젠가 사랑한다. 대답은 완벽했습니다, 정말 고마워요. – GPH