Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
I have the sample data like this
student_id  metric         score
1          raw_score        20
1          scale_score       30
2          proficiency      level1
2          scale_score      60   
3          raw_score        45
3          proficiency      level2
4          scale_score       54
4          proficiency       level2


the expected output is

studentid raw_score scale_score proficiency
1            20         30          null
2            null        60         level1
3            45          null        level2
4             null        54         level2


Thannks in advance.

Regards,
Prakash
Posted
Updated 11-Sep-13 8:49am
v2
Comments
Corporal Agarn 11-Sep-13 14:51pm    
What is the problem? What is your code?

Please, have a look:

SQL
CREATE TABLE #exdata (student_id  INT, metric VARCHAR(30), score VARCHAR(30))

INSERT INTO #exdata (student_id, metric, score)
SELECT 1, 'raw_score', '20'
UNION ALL SELECT 1, 'scale_score', '30'
UNION ALL SELECT 2, 'proficiency', 'level1'
UNION ALL SELECT 2, 'scale_score', '60'
UNION ALL SELECT 3, 'raw_score', '45'
UNION ALL SELECT 3, 'proficiency', 'level2'
UNION ALL SELECT 4, 'scale_score', '54'
UNION ALL SELECT 4, 'proficiency', 'level2'

DECLARE @cols VARCHAR(300)
DECLARE @dt VARCHAR(2000)
DECLARE @pt VARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT '],[' + metric
            FROM #exdata
            ORDER BY '],[' + metric
            FOR XML PATH('')),1,2,'') + ']'

--SELECT @cols As cols

SET @dt = N'SELECT *
        FROM #exdata'
--EXEC(@dt)

SET @pt = N'SELECT student_id, ' + @cols + ' ' +
            'FROM(' + @dt + ') AS DT ' +
            'PIVOT(MAX(score) FOR metric IN(' + @cols + ')) AS PT'
EXEC(@pt)

DROP TABLE #exdata


Result:
student_id	proficiency	raw_score	scale_score
1		NULL		20		30
2		level1		NULL		60
3		level2		45		NULL
4		level2		NULL		54
 
Share this answer
 
Comments
thatraja 12-Sep-13 9:32am    
5!I think you have plenty of free time.
Maciej Los 12-Sep-13 10:23am    
Thank you ;)

Time is a relative term. It depends on which side of the door to the toilet we are standing ;)
 
Share this answer
 
Comments
Maciej Los 12-Sep-13 10:24am    
+5!
Have you got LinkedIn account?
thatraja 12-Sep-13 10:29am    
yes, thatraja is id
Maciej Los 12-Sep-13 10:44am    
I can't find it ;(
thatraja 12-Sep-13 10:50am    
in.linkedin.com/in/thatraja
thatraja 12-Sep-13 10:51am    
I forgot to include this link in my site.
SQL
SELECT student_id,raw_score,scale_score,proficiency FROM
(SELECT student_id,metric,score FROM Temp123)p
PIVOT(MAX(score) FOR metric IN(raw_score,scale_score,proficiency)) AS pvt
 
Share this answer
 

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