| Author |
Topic |
|
Bertin
Starting Member
7 Posts |
Posted - 2011-04-04 : 06:18:13
|
| I have a table TestResults with columns: studentID, test, score. Filled with data like1, math, 751, english, 801, biologie, 452, math, 602, english, 902, biologie, 303, math, 453, english, 903, biologie, 72I want to present the results in a table with one row per student so:clientID, math, english, biologie1, 75, 80, 452, 60, 90, 303, 45, 90, 72can I do this with a query ? |
|
|
theboyholty
Posting Yak Master
226 Posts |
Posted - 2011-04-04 : 06:26:53
|
| [code]CREATE TABLE TestResults (StudentID INT,Subject VARCHAR(30),Grade INT)INSERT INTO TestResults SELECT 1 as StudentID, 'math' as Subject, 75 as Grade UNION ALLSELECT 1, 'english', 80 UNION ALLSELECT 1, 'biologie', 45 UNION ALLSELECT 2, 'math', 60 UNION ALLSELECT 2, 'english', 90 UNION ALLSELECT 2, 'biologie', 30 UNION ALLSELECT 3, 'math', 45 UNION ALLSELECT 3, 'english', 90 UNION ALLSELECT 3, 'biologie', 72SELECT StudentID ,SUM(CASE WHEN [Subject] = 'math' THEN Grade END) AS mathGrade ,SUM(CASE WHEN [Subject] = 'english' THEN Grade END) AS englishGrade ,SUM(CASE WHEN [Subject] = 'biologie' THEN Grade END) AS biologieGradeFROM TestResultsGROUP BY StudentID[/code]The above code would work IF you knew previously what your definitive list of subjects would be AND you wouldn't get more than one result per subject per student because it uses the SUM function. You could use MAX or MIN just as well or if a grade was altered, you could mark the old grade as deleted and then write that into the code.Perhaps a better solution would be to use PIVOT, but it would take someone else to explain that as I'm only just learning about it myself.---------------------------------------------------------------------------------http://www.mannyroadend.co.uk The official unofficial website of Bury Football Club |
 |
|
|
|
|
|