[英]See how many times condition met
I have a table (stu_grades) that stores student data and their grades. 我有一个表(stu_grades),用于存储学生数据及其成绩。
I want to find out how many times for eg each student in that table got 'A' and then 'B' etc. 我想找出例如该表中的每个学生获得“ A”然后是“ B”等的次数。
How do i do this? 我该怎么做呢? my feeling is to use a row over? 我的感觉是要用完吗? by i can't construct the query. 通过我无法构造查询。
stu_grades stu_grades
stu_ID|grade1|grade2|Grade3
1 A A C
2 B B B
3 C C A
1 C A C
the same student could occur more than once in the table with the same grades or even a different grade. 同一名学生在同一等级甚至不同等级的表中可能出现多次。
I especially want to check where the grade has appeared more than 3 or more times 我特别想检查成绩出现过3次以上的地方
So the final output should be like: 因此,最终输出应为:
Stu_ID|Grade|Count
1 A 3
1 C 3
2 B 3
3 C 2
3 A 1
Use the Group BY
: 使用Group BY
依据:
SELECT stu_ID, Grade, GradeCount
FROM stu_grades
LEFT OUTER JOIN
(
SELECT Grade, COUNT(Grade) GradeCount
FROM stu_grades
GROUP BY Grade
)tb
ON tb.Grade= stu_grades.Grade
您可以使用GROUP BY和HAVING子句解决此问题
SELECT grade, COUNT(grade) FROM stu_grades GROUP BY grade HAVING COUNT(grade) > 3
You mentioned that you wanted the grade count per student per grade. 您提到想要每个学生每个年级的成绩计数。 You would need to group by both stu_id and grade. 您将需要按stu_id和等级进行分组。
SELECT stu_id, grade, COUNT(grade) GradeCount
FROM stu_grades
GROUP BY stu_id, grade
HAVING COUNT(grade) > 3
1) Normalize your data: 1)规范化您的数据:
select stu_id, grade
from stu_grades, unnest(array[grade1, grade2, grade3]) as g(grade);
2) For now it is easy: 2)现在很容易:
select stu_id, grade, count(*)
from stu_grades, unnest(array[grade1, grade2, grade3]) as g(grade)
group by 1, 2 order by 1, 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.