Since you have multiple Telephone
values for each Customer
, the easiest way to get the result would be to use a windowing function like row_number
to create a unique value for each Telephone
/Customer
combination. Once you have this value, then you can PIVOT
the result using an aggregate function and CASE expression or the PIVOT function.
Having up to five telephone numbers, makes this easy to write the query as a hard-coded or static version. Using an aggregate function with a CASE expression the code would be:
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;
See SQL Fiddle with Demo
If you want to use the PIVOT function, then the code would be:
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
See SQL Fiddle with Demo. Both give a result:
| CUSTOMER | TEL1 | TEL2 | TEL3 | TEL4 |
|----------|------------|------------|--------|--------|
| 74270571 | 1556589962 | 7756563729 | (null) | (null) |