June 28, 2010 at 6:37 pm
Hi,
I've a query in which i need to change some of the columns into rows.
Please see the example;
Existing query
--------------
[Emp_Name] [PHN] [MOB] [OTH]
[Steve] [223] [456] [895]
[John] [789] [789] [421]
[jack] [ ] [252] [252]
I need this query to be changed in a format like this..
[Emp_Name] [NMBR] [TYP]
[Steve] [223] [P]
[Steve] [456] [M]
[Steve] [895] [O]
[John] [789] [P+M]
[John] [421] [O]
[jack] [252] [M+O]
Please let me know that if anyone got logic..
Regards
Robz
June 28, 2010 at 8:44 pm
hi there...
try this. to convert columns into rows, you need to use UNPIVOT.
declare @table table(
[Emp_Name] varchar(50),
[MOB] int,
[PHN] int,
[OTH] int
)
insert @table ([Emp_Name], [PHN], [MOB] ,[OTH])
select 'Steve' ,223 ,456 ,895
union all select 'John' ,789 ,789 ,421
union all select 'jack' , null, 252, 252
SELECT [Emp_Name] ,PhoneDesc,PhoneNumbers FROM
(select [Emp_Name], [PHN], [MOB] ,[OTH] From @table ) PIVOT_TABLE
UNPIVOT
( PhoneNumbers for PhoneDesc in ([PHN], [MOB] ,[OTH])) PIVOT_HANDLE
And this seems to a homework to me.. if it were, then me providing code and u submitting it wont help you to learn! 🙁
anyways, hope it helps...
June 28, 2010 at 9:56 pm
Hi..
This may produce your expected result.. I just added logic to concatenate the values from unpivoted table..
DECLARE @table TABLE (Emp_Name VARCHAR(50),PHN INT, MOB INT, OTH INT)
INSERT INTO @table
SELECT 'Steve',223,456,895 UNION ALL
SELECT 'John',789,789,421 UNION ALL
SELECT 'jack',NULL,252,252
SELECTEmp_Name
,temp.NMBR
,STUFF((ISNULL('+' + (MAX(CASE WHEN type='PHN' THEN 'P' END)),'') +
ISNULL('+' + (MAX(CASE WHEN type='MOB' THEN 'M' END)),'') +
ISNULL('+' + (MAX(CASE WHEN type='OTH' THEN 'O' END)),'')),1,1,'') AS [Type]
FROM@table
UNPIVOT(
NMBR FOR [Type] IN (PHN,MOB,OTH)
) temp
GROUP BY Emp_Name,NMBR
ORDER BY Emp_Name
Hope this helps.. 🙂
Cheers!
June 29, 2010 at 5:09 am
Thanx very much.. it works.. i could easily change it to my intended code..
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply