[英]Selecting a COUNT of values, grouped by that same column, distinct on another
[英]How to get distinct count of a column with respective to distinct values of another column in same table?
我有包含学生 id、班级、部分、科目 id、总分和 isPassed 状态的分数表(1=通过,0=失败)。 我想要一个班级或部分中所有科目的 isPassed 状态为 1 的学生总数。 我的查询如下所示:
$pass = Marks::select('student_id')
->where('class_room_id', '=', 10)
->where('section_id', '=', 1)
->where('isPassed', '=', 1)
->distinct()
->get();
$passed = count($pass);
该表看起来像:
student_id subject_id isPassed
1001 100 1
1001 101 0
1001 102 1
1001 103 1
1001 104 1
1002 100 1
1002 101 1
1002 102 1
1002 103 1
1002 104 1
你的 SQL 查询应该是这样的:
SELECT COUNT(student_id)
FROM marks
WHERE class_room_id = 10
AND student_id NOT IN (SELECT student_id FROM marks WHERE class_room_id = 10 AND isPassed = 0)
嵌套查询SELECT student_id FROM marks WHERE class_room_id = 10 AND isPassed = 0
选择给定班级中至少有一个isPassed = 0
测试的所有学生。 这些是您不需要的学生。
更新
好的,在获得您在评论中提供的所有信息后,这里是答案。
您要查找的查询是:
SELECT COUNT(DISTINCT student_id)
FROM tbl2
WHERE student_id NOT IN (SELECT student_id FROM tbl2 WHERE isPassed = 0)
它获取通过所有科目的学生人数。
嵌套查询是:
SELECT student_id FROM tbl2 WHERE isPassed = 0
它得到至少失败一次的学生。
一个 SQLFiddle 来演示它: http ://sqlfiddle.com/#!9/a6baf4/1
您可以使用聚合函数来获取每组的计数
Marks::where('section_id', '=', 1)
->where('isPassed', '=', 1)
->groupBy('class_room_id')
->selectRaw('COUNT(1) as studentCount')
->get();
此查询将为每个class_room_id
返回一行,其值为studentCount
。 如果您只需要一间或几间教室,您可以向查询添加 where 过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.