在SQL查询中添加一列,该列只应包含筛选结果

在SQL查询中添加一列,该列只应包含筛选结果,sql,pivot,aggregate-functions,Sql,Pivot,Aggregate Functions,我有下表: TABLE +--------------------------+ | STUDENT CLASS SCORE | +--------------------------+ | Student1 Science Pass | | Student1 Math Fail | | Student1 Geography Fail | | Student2 Science Pass | | Student2 Math Pass | | Stud

我有下表:

TABLE
+--------------------------+
| STUDENT  CLASS     SCORE |
+--------------------------+
| Student1 Science   Pass  |
| Student1 Math      Fail  |
| Student1 Geography Fail  |
| Student2 Science   Pass  |
| Student2 Math      Pass  |
| Student2 Geography Fail  |
+--------------------------+
我希望看到如下结果

+------------------------------------+
| STUDENT  Science   Math  Geography |
+------------------------------------+
| Student1 Pass     Fail   Fail      |
| Student2 Pass     Pass   Fail      |
+------------------------------------+

你知道我如何做到这一点吗?

对于固定的类列表,你可以使用条件聚合:

select student,
    max(case when class = 'Science'   then score end) as science,
    max(case when class = 'Math'      then score end) as math,
    max(case when class = 'Geography' then score end) as geography
from mytable
group by student

对于固定的类列表,您可以只使用条件聚合:

select student,
    max(case when class = 'Science'   then score end) as science,
    max(case when class = 'Math'      then score end) as math,
    max(case when class = 'Geography' then score end) as geography
from mytable
group by student

请注意为正确重新格式化问题所做的编辑,如果要进行任何更新,请保留格式(或至少比原始格式更好)。请注意为正确重新格式化问题所做的编辑,如果要进行任何更新,请保留格式(或者至少,比原版更好的东西)。这就像一个符咒!!谢谢你的快速反应!!这就像一个符咒!!谢谢你的快速反应!!