【问题标题】:Finding count of fields in DB with special condition查找具有特殊条件的数据库中的字段数
【发布时间】:2020-07-22 15:19:56
【问题描述】:

我的问题是: 如果我有带有 student_id 和其他字段的表学生(没关系) 以及包含三个字段的表格考试:student_id、subject_id(来自另一个表格主题的id)和exam_mark。

我需要计算每个科目的考试成绩相同的学生人数。

我一直坚持这项任务,您可以告诉我如何做或解释完整的解决方案。

简单数据:

对于这种情况,查询必须返回 count(student_id) = 4

【问题讨论】:

  • 请提供样本数据和期望的结果。
  • @GordonLinoff 我编辑了问题

标签: sql postgresql


【解决方案1】:

你需要嵌套聚合:

select count(*)
from
 (
   select student_id
   from tab
   group by student_id
   -- same min and max means only one value exists
   having min(exam_mark) = max(exam_mark)
 ) as dt

最小值/最大值通常比COUNT(DISTINCT exam_mark) = 1 更有效。

如果您只希望学生有多个分数,请增强 HAVING

    AND count(*) > 1

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多