는 결과를 얻을 수있는 가장 쉬운 방법은 각 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) |
나는이 장소를 언젠가 사랑한다. 대답은 완벽했습니다, 정말 고마워요. – GPH