2

I have seen a lot of posts and topics regarding pivots and transposing data, I'm either not understanding them (likely) or I'm trying to over complicate what I need to do.

I'm running a simple select statement like so:

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

This returns:

Customer | Telephone
74270571 | 01556589962
74270571 | 07756563729

And what I am trying to get is

Customer | Tel1         | Tel2
74270571 | 01556589962  | 07756563729

There can be a max of 5 tel numbers.

1 Answer 1

1

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) |
1
  • I honestly love this place some days. The answer was perfect, Thank you so much.
    – GPH
    Jan 29, 2015 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.