我有一个存储过程,我希望返回一个结果集,如下所示:
id | student | term1 | term2
问题是数据不会像这样存储在数据库中。因此查询将生成一个如下所示的结果集:
id | student | termNo | termValue
1 | lorem | 1 | someValue
2 | ipsum | 2 | anotherValue
有没有简单的方法来转换它。结果集很大,所以我不想做几个明显的解决方案。
希望这是可以理解的=)
答案 0 :(得分:3)
好的,根据你的评论,你可以这样做:
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
或
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