[英]SQL - for each id, count how many entries in one column is greater than another
Suppose I have a table 'results' that looks like this:假设我有一个如下所示的表格“结果”:
student | score | passing_grade
1 | 50 | 70
1 | 30 | 50
2 | 90 | 50
2 | 80 | 100
I want to count, for each student, how many tests they've passed.我想为每个学生数一数他们通过了多少次考试。 The result should be as followed:结果应如下所示:
student | passed
1 | 0
2 | 1
explanation: student 1 has passed none of the tests, while student 2 has passed 1 out of 2 tests based on the conditions of the second and third column.解释:学生 1 没有通过任何测试,而学生 2 根据第二列和第三列的条件通过了 2 次测试中的 1 次。
I don't know if it makes a difference but I created results by merging 2 tables together.我不知道这是否有所作为,但我通过将 2 个表合并在一起创建了结果。 I've tried to use the WHERE clause to find all rows where the score > passing_grade but I don't know if that is in the right direction.我尝试使用 WHERE 子句查找 score > pass_grade 的所有行,但我不知道这是否是正确的方向。 I've also tried the COUNT(CASE WHEN score > passing_grade THEN 1 ELSE 0 END) but I'm not sure if I'm doing it right since this counts every row.我也尝试过 COUNT(CASE WHEN score > passing_grade THEN 1 ELSE 0 END) 但我不确定我是否做对了,因为这对每一行都很重要。
It's a simple SQL query.这是一个简单的 SQL 查询。 I would recommend reading SQL basics and trying a bit before posting a question.我建议阅读 SQL 基础知识并在发布问题之前尝试一下。 But since you're a new contributor here (welcome aboard ), including the query which might help:但是由于您是这里的新贡献者(欢迎加入),包括可能有帮助的查询:
SELECT
student,
count(*) as passed
FROM results
WHERE
score > passing_grade
GROUP BY
student
;
Your COUNT
logic is basically correct except that the ELSE
non null value is causing every record to be counted as one.您的COUNT
逻辑基本上是正确的,除了ELSE
非 null 值导致每条记录都被计为一个。 The COUNT
function ignores only nulls, so the ELSE
value should either be null or ELSE
should be omitted entirely: COUNT
function 仅忽略空值,因此ELSE
值应为 null 或ELSE
应完全省略:
SELECT student, COUNT(CASE WHEN score > passing_grade THEN 1 END) AS passed
FROM results
GROUP BY student;
Note that MySQL supports summing boolean expressions directly, so we can make the above even tighter:请注意,MySQL 支持直接对 boolean 表达式求和,因此我们可以使上面的表达式更严格:
SELECT student, SUM(score > passing_grade) AS passed
FROM results
GROUP BY student;
SELECT C.STUDENT,
SUM(
CASE
WHEN C.SCORE>=C.PASSING_GRADE THEN 1
ELSE 0
END
)AS PASSED
FROM RESULTS AS C
GROUP BY C.STUDENT
The same logic, but with SUM-function相同的逻辑,但具有 SUM 功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.