【问题标题】:Add a column in an SQL query that should only filtered results在 SQL 查询中添加仅应过滤结果的列
【发布时间】:2021-03-06 10:35:37
【问题描述】:

我有下表:

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      |
+------------------------------------+

知道如何做到这一点吗?

【问题讨论】:

  • 请注意修改以正确重新格式化您的问题,如果您有任何更新,请保留格式(或至少比原始格式更好)。

标签: sql pivot aggregate-functions


【解决方案1】:

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

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

【讨论】:

  • 这就像一个魅力!感谢您的快速回复!
猜你喜欢
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多