Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
dear sir/ma'am

can anybody help me in framing this query :Following are the input & output
Input table:

Empno PhoneType Number
100   Mobile    1234
100   Telephone 3456
101   Mobile    5678
102   Telephone 7890
103   Mobile    3412

Output:
Empno Mobile Telephone
100   1234   3456
101   5678   -
102   -      7890
103   3412   -
Posted
Updated 3-Jul-13 1:10am
v2

Try this:
SQL
DECLARE @PhoneDtls TABLE (Empno INT, PhoneType VARCHAR(20), Number VARCHAR(20))

INSERT INTO @PhoneDtls(EmpNo,PhoneType,Number)
SELECT 100,'Mobile','1234'
UNION ALL SELECT 100,'Telephone','3456'
UNION ALL SELECT 101,'Mobile','5678'
UNION ALL SELECT 102,'Telephone','7890'
UNION ALL SELECT 103,'Mobile','3412'
SELECT EmpNo,PhoneType,Number FROM @PhoneDtls

SELECT Empno, ISNULL([Mobile],'-') 'Mobile', ISNULL([Telephone] ,'-') 'Telephone'
FROM (
    SELECT *
    FROM @PhoneDtls
) AS DT
PIVOT(MAX([Number]) FOR [PhoneType] IN([Mobile], [Telephone])) AS PT


More: Using PIVOT and UNPIVOT[^]
 
Share this answer
 
v5
Comments
ankur789 3-Jul-13 7:16am    
incorrect syntax near pivot
Maciej Los 3-Jul-13 7:26am    
Check now ;)
ankur789 3-Jul-13 7:28am    
Sir incorrect syntax near pivot
Maciej Los 3-Jul-13 7:32am    
Now, should be OK ;)
gvprabu 4-Jul-13 6:57am    
hi check the solution... there is no error in this
Hi,

Try the below Code...

SQL
DECLARE @PhoneDtls TABLE (Empno INT, PhoneType VARCHAR(20), Number VARCHAR(20))

INSERT INTO @PhoneDtls(EmpNo,PhoneType,Number)
SELECT 100,'Mobile','1234'
UNION ALL SELECT 100,'Telephone','3456'
UNION ALL SELECT 101,'Mobile','5678'
UNION ALL SELECT 102,'Telephone','7890'
UNION ALL SELECT 103,'Mobile','3412'
SELECT EmpNo,PhoneType,Number FROM @PhoneDtls


SELECT T.EmpNo, 
	ISNULL((SELECT Number FROM @PhoneDtls WHERE PhoneType ='Mobile' AND EmpNo=T.EmpNo),'-') 'Mobile',
	ISNULL((SELECT Number FROM @PhoneDtls WHERE PhoneType ='Telephone' AND EmpNo=T.EmpNo),'-') 'Number'
FROM (SELECT DISTINCT EmpNo FROM @PhoneDtls) T

Regards,
GVPrabu
 
Share this answer
 
v3
Comments
ArunRajendra 4-Jul-13 4:43am    
This will not give the recored in same row. The resut will be shown in two rows.
gvprabu 4-Jul-13 6:53am    
I updated my solution, check it now.
gvprabu 4-Jul-13 4:48am    
yes correct... I will change the code. Thanks
ankur789 4-Jul-13 5:13am    
This will not give the recored in same row. The resut will be shown in two rows.
I wants result in one row
Maciej Los 4-Jul-13 6:39am    
See my solution.
Is there something wrong with it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900