The problem I’m having is that there are more than one result in a table for what I’m trying to find. So if I have this:
SELECT DISTINCT student.ident AS [Ident],
proghist.prgc AS [Test Code]
FROM student
LEFT OUTER JOIN proghist
For some students I get multiple “Test Codes” so it’ll look like this:
Ident Test Code
123456 1
123456 4
654321 2
654321 6
122222 1
Is there a way to combine them to one row and separate columns?
Edit: I would like the data to be in the final result:
123456 1 4
654321 2 6
122222 1
Since you are using SQL Server, if you are using SQL Server 2005+, then you can use the
PIVOTfunction. If you know you will only have up to twoTestCodesperidentthen you can hard-code the values:See SQL Fiddle with Demo
If you have an unknown number of values of
TestCodes, then you can use dynamic SQL toPIVOTthe data:See SQL Fiddle with Demo
If you do not have access to the
PIVOTfunction, then you can use an aggregate function with aCASEstatement:See SQL Fiddle with Demo
All three will produce the same result: