Reputation: 103
So Here it is : I joined several tables and get results like this:
ContactID Name Title Phone
1234567 John Manager 999999
1234567 John Manager 888888
I want to get the unique ContactID in my result and put another phone value to 'Phone2'. (There are more than 2, Phone3, Phone4)
So the result I want to see is like this
ContactID Name Title Phone Phone2 Phone3 Phone4...
1234567 John Manager 999999 888888 NULL NULL
Any help? I tried to use Pivot, but it seems like the aggregate function wont work in this scenario.
Upvotes: 0
Views: 2164
Reputation: 107786
You can still use a PIVOT, although you have to make up a pivot column, for which I use the ROW_NUMBER() function below. I have allowed for 4 phone numbers below, just expand the pattern, e.g. there are 2 places with [4]
, if you need to cater for more.
Below I show data coming from a sample table named "data". If you have a complex query, you can first name it using a Common Table Expression, i.e.
;with data as (
<your entire complex query that produces the
columns: ContactId, Name, Title, Phone>
)
select ContactID, Name, Title,
[1] as Phone1,
[2] as Phone2,
[3] as Phone3,
[4] as Phone4
from (
select ContactID, Name, Title, Phone,
Row_Number() over (partition by ContactID, Name, Title
order by Phone) RN
from data) p
pivot (max(Phone) for RN in ([1],[2],[3],[4])) v;
MS SQL Server 2012 Schema Setup:
create table data (
ContactID int,
Name varchar(10),
Title varchar(10),
Phone varchar(20));
insert data values
(1234561, 'Jill', 'Employee', 999991),
(1234562, 'Joel', 'Employee', 999992),
(1234567, 'John', 'Manager', 999999),
(1234567, 'John', 'Manager', 888888);
Query 1:
select ContactID, Name, Title,
[1] as Phone1,
[2] as Phone2,
[3] as Phone3,
[4] as Phone4
from (
select ContactID, Name, Title, Phone,
Row_Number() over (partition by ContactID, Name, Title
order by Phone) RN
from data) p
pivot (max(Phone) for RN in ([1],[2],[3],[4])) v;
| CONTACTID | NAME | TITLE | PHONE1 | PHONE2 | PHONE3 | PHONE4 |
-------------------------------------------------------------------
| 1234561 | Jill | Employee | 999991 | (null) | (null) | (null) |
| 1234562 | Joel | Employee | 999992 | (null) | (null) | (null) |
| 1234567 | John | Manager | 888888 | 999999 | (null) | (null) |
Upvotes: 1
Reputation: 2321
If you want you can get all the phone numbers into one column which might be more useful for you depending on your situation.
First Last Phone John Manager 888888,999999,111111
Upvotes: 0