简体   繁体   中英

See how many times condition met

I have a table (stu_grades) that stores student data and their grades.

I want to find out how many times for eg each student in that table got 'A' and then 'B' etc.

How do i do this? my feeling is to use a row over? by i can't construct the query.

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

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 :

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.

  SELECT stu_id, grade, COUNT(grade) GradeCount
  FROM stu_grades
  GROUP BY stu_id, grade
  HAVING COUNT(grade) > 3

1) Normalize your data:

select stu_id, grade
from stu_grades, unnest(array[grade1, grade2, grade3]) as g(grade);

2) For now it is easy:

select stu_id, grade, count(*)
from stu_grades, unnest(array[grade1, grade2, grade3]) as g(grade)
group by 1, 2 order by 1, 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM