Reputation: 6656
I have a stored procedure in which I would like to return a result set looking something like this:
id | student | term1 | term2
The problem is that the data isn't stored like this in the db. So the query will generate a result set looking something like this:
id | student | termNo | termValue
1 | lorem | 1 | someValue
2 | ipsum | 2 | anotherValue
Is there any simple way to convert this. The result sets is large, so I don't want to make several queries which would be the obvious solution.
Hope this is understandable =)
Upvotes: 0
Views: 128
Reputation: 70638
Ok, based on your comment, you can do this:
SELECT id,
student,
MIN(CASE WHEN termNo = 1 THEN termValue END) term1,
MIN(CASE WHEN termNo = 2 THEN termValue END) term2,
MIN(CASE WHEN termNo = 3 THEN termValue END) term3,
MIN(CASE WHEN termNo = 4 THEN termValue END) term4
FROM YourTable
GROUP BY id, student
or
SELECT id, student, [1] AS Term1, [2] AS Term2, [3] AS Term3, [4] AS Term4
FROM YourTable T
PIVOT(MIN(termValue) FOR termNo IN ([1],[2],[3],[4])) AS PT
Upvotes: 3