txdolfan
asked on
SQL Piviot Functionality
I have a table that contains many rows of data for a unique account number:
uid number phone_number
1 987 9725551212
2 987 9725551212
3 987 4695551212
4 987 2145551212
I need to remove the duplicates and create a single row of the data with the number and each unique phone_number.
number, phone_number1, phone_number2, phone_number3..... phone_number15
I cannot seem to get all the numbers uniquely.
uid number phone_number
1 987 9725551212
2 987 9725551212
3 987 4695551212
4 987 2145551212
I need to remove the duplicates and create a single row of the data with the number and each unique phone_number.
number, phone_number1, phone_number2, phone_number3..... phone_number15
I cannot seem to get all the numbers uniquely.
you can do something like this
;with CTE as (
select distinct number, phone_number
from yourtable
)
select distinct
number,
stuff((select ',' + phone_number from CTE where number = a.number for xml path('')), 1, 2, '') as phone_numbers
from CTE a
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you want it in separate columns then you can do something like the below:
declare @cols varchar(max)
declare @strSQL varchar(max)
set @cols = stuff((select '], [' + cast(rn as varchar(10)) from (
select distinct
number,
phone_number,
row_number() over (partition by number order by phone_number) rn
from yourtable
) a for xml path('')
), 1, 1, '') + ']'
set @strSQL = 'select number, ' + @cols
+ ' from (
select distinct
number,
phone_number
row_number() over (partition by number order by phone_number) rn
from yourtable
) o
pivot (max(phone_number) for rn in (' + @cols + ')) as p'
exec(@strSQL)
correction in line 4 above
declare @cols varchar(max)
declare @strSQL varchar(max)
set @cols = stuff((select distinct '], [' + cast(rn as varchar(10)) from (
select distinct
number,
phone_number,
row_number() over (partition by number order by phone_number) rn
from yourtable
) a for xml path('')
), 1, 1, '') + ']'
set @strSQL = 'select number, ' + @cols
+ ' from (
select distinct
number,
phone_number
row_number() over (partition by number order by phone_number) rn
from yourtable
) o
pivot (max(phone_number) for rn in (' + @cols + ')) as p'
exec(@strSQL)
ASKER
This solution worked right out of the gate (after table name mods) and ran really clean. Thank you all for the suggestions I really appreciate it.
If you sort according to number (I suppose that number identifies the person whichs phone_number it is) you'll receive something like this:
uid number phone_number
1 987 9725551212
3 987 4695551212
4 987 2145551212
If you need a table like this:
uid number phone_number phone_number2 phone_number3 ...
1 987 9725551212 4695551212 2145551212 ...
... then you should either play with the data from the select below in Excel or write a MSSQL functions (eg. get_nth_phone_number(numbe
Open in new window