I have tried using Case-End but nothing worked.
Diff types of phone number are :
- Home
- Cell
- Main
- OTPR
- Busn
I have tried using Case-End but nothing worked.
Diff types of phone number are :
select emplid,
max(case when phone_type='home' then phone_number else -1 end) Home,
max(case when phone_type='cell' then phone_number else -1 end) Cell,
.....
from phone_data
group by emplid;
You can't mix character and numeric in one field, if you require n/a in the output you need another step which makes the phone number columns characters.
select t.empid as empid, cell.phone_number as cell, home.phone_number as Home
from telephones t
inner join telephones cell on t.empid = cell.empid
inner join telephones home on t.empid = home.empid
where cell.Phone_type = "cell"
and home.Phone_type = "home"
group by t.empid
and a sql fiddle : http://sqlfiddle.com/#!2/6bb17/11
Try this SQL query!
DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phone_type)
FROM youtablename c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT empid, ' + @cols + ' from
(
select empid
, phone_number
, phone_type
from youtablename
) x
pivot
(
max(phone_number)
for phone_type in (' + @cols + ')
) p '
execute(@query)