简体   繁体   English

查看满足条件的次数

[英]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.

相关问题 如何查看是否满足某些条件,并以此为基础显示结果 - How to see if some condition is met, and based on that to display result 计算满足条件时列中position前面有多少行 - Calculate how many rows are ahead of position in column when condition is met SQL 查询以查看是否满足条件,仅此而已 - SQL query to see if condition is met and nothing else 计算在条件触发后条件触发MySQL的次数 - Count how many times a condition is triggered in MySQL into a time lapse SQL 查询具有多对多关系且必须满足一个条件的 2 个表 - SQL Query with 2 tables with many to many relations and one condition must be met 如果不满足条件,我如何接收一对与第二个 ID 的 null 值具有多对多关系的实体 ID - How do I receive a pair of ids of entities in many-to-many relation with null value for the second id if condition is not met 查找条件满足x在mysql / sql中的次数的记录 - Find records where condition met x number of times in mysql/sql 我如何查看一个人每月来过几次(SQL) - How can I see how many times a person came per month (SQL) 仅在TSQL中满足条件时才选择列 - How to select a column only if condition is met in TSQL 如果不满足条件,如何使存储过程失败 - How to make stored procedure fail if condition is not met
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM