Home > Database > Mysql Tutorial > Mysql implements how to write sql to obtain the top few in each group after distinguishing by group

Mysql implements how to write sql to obtain the top few in each group after distinguishing by group

王林
Release: 2023-05-31 09:01:24
forward
1716 people have browsed it

    Encountered a scenario where I need to group the data and then get the first 10 pieces of data in each group. First I thought of using group by, but the difficulty is how to know the data after grouping. The data is ranked in the group.

    1. Create a table and insert relevant test data

    CREATE TABLE `score` (
      `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
      `subject` varchar(20) DEFAULT NULL COMMENT '科目',
      `student_id` int(11) DEFAULT NULL COMMENT '学生id',
      `student_name` varchar(20) NOT NULL COMMENT '学生姓名',
      `score` double DEFAULT NULL COMMENT '成绩',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
    Copy after login

    Mysql implements how to write sql to obtain the top few in each group after distinguishing by group

    Note: The inserted data sql is at the end, friends can verify the following by themselves sql

    2. Query the records of the top three scores in each subject

    Now that the data is available, write the sql. The sql is as follows:

    ###每科成绩前三名
    SELECT
    	* 
    FROM
    	score s1 
    WHERE
    	( SELECT count( * ) FROM score s2 
    	           WHERE s1.`subject` = s2.`subject` AND s1.score < s2.score 
    	) < 3 
    ORDER BY
    	SUBJECT,
    	score DESC
    Copy after login

    Mysql implements how to write sql to obtain the top few in each group after distinguishing by group

    Analysis:

    A subquery is used in it, and the core sql is the condition after where:

    ( SELECT count( * ) FROM score s2 WHERE s1.subject = s2.subject AND s1.score < s2.score ) < 3
    Copy after login

    The meaning of this sql is. . .

    I feel like my language is a bit difficult to describe, so I will use the java code I am familiar with to describe the above sql. It is probably a for loop that traverses twice, and the same subject is counted in the second for loop. Student records, the number of students with higher scores than s1. If this number is less than 3, it means that s1 ranks in the top three. Look at the following code to understand

    public class StudentTest {
       
        public static void main(String[] args) {
            List<Student> list = new ArrayList<>();
            //初始化和表结构一致的数据
            initData(list);
            //记录查询出来的结果
            List<Student> result = new ArrayList<>();
            for(Student s1 : list){
                int num = 0;
                //两次for循环遍历,相当于sql里面的子查询
                for(Student s2:list){
                    //统计同一科目,且分数s2分数大于s1的数量,简单理解就是同一科目的学生记录,比s1的学生分数高的数量
                    if(s1.getSubject().equals(s2.getSubject())
                            &&s1.getScore()<s2.getScore()){
                        num++;
                    }
                }
                //比s1的学生分数高的数量,如果小于3的话,说明s1这个排名前三
                // 举例:num=0时,说明同一科目,没有一个学生成绩高于s1学生, s1学生的这科成绩排名第一
                // num =1,时,s1学生排名第二,num=3时:说明排名同一科目有三个学生成绩高过s1,s1排第四,所以只统计前三的学生,条件就是num<3
                if(num < 3){
                    result.add(s1);
                }
            }
            //输出各科成绩前三的记录
            result.stream()
                    .sorted(Comparator.comparing(Student::getSubject))
                    .forEach(
                 s-> System.out.println(String.format("学生:%s,科目:%s,成绩:%s",s.getName(),s.getSubject(),s.getScore()))
            );
    
        }
    
        public static void initData(List<Student> list) {
             
               list.add(new Student(1,"语文","张三",59));
               list.add(new Student(2,"数学","张三",78));
               list.add(new Student(3,"英语","张三",65));
               list.add(new Student(4,"语文","李四",88));
               list.add(new Student(5,"数学","李四",58));
               list.add(new Student(6,"英语","李四",65));
               list.add(new Student(7,"语文","王五",92));
               list.add(new Student(8,"数学","王五",99));
               list.add(new Student(9,"英语","王五",96));
               list.add(new Student(10,"语文","小张",90));
               list.add(new Student(11,"数学","小张",91));
               list.add(new Student(12,"英语","小张",90));
               list.add(new Student(13,"语文","小华",88));
               list.add(new Student(14,"数学","小华",79));
               list.add(new Student(15,"英语","小华",77));
        }
        
        @Data
        public static class Student {
        private int id;
        private String subject;
        private String name;
        private double score;
        //想当于表结构
        public Student(int id, String subject, String name, double score) {
            this.id = id;
            this.subject = subject;
            this.name = name;
            this.score = score;
        }
    }
    Copy after login

    You can see the results and execution printed out after the code is run. The result after sql is the same

    Mysql implements how to write sql to obtain the top few in each group after distinguishing by group

    ##3. Query the records of students whose scores in each subject are greater than or equal to 90 points

    The table and data are available. By the way, Summarize some sql questions of this type

    If the question is to query the records in the above table whose scores in each subject are greater than or equal to 90 points, then how to write the sql?

    1. The first way to write: Positive thinking

    If the scores in each subject are greater than 90 points, then the lowest score must also be greater than or equal to 90 points. The sql is as follows:

    SELECT
    	* 
    FROM
    	score 
    WHERE
    	student_id IN  
    	  (SELECT student_id FROM score GROUP BY student_id HAVING min( score ) >= 90 )
    Copy after login

    2. The second way of writing: reverse thinking

    Exclude records with the highest score less than 90 points

    SELECT
    	* 
    FROM
    	score 
    WHERE
    	student_id NOT IN  
    	  (SELECT student_id FROM score GROUP BY student_id HAVING max( score ) < 90 )
    Copy after login

    Note: Forward and reverse options depend on the specific situation

    Other narration

    Query the records of students whose average score in each subject is greater than 80 points

    ###查询学生各科平均分大于80分的记录
    select * from score where student_id in(
         select student_id from score GROUP BY student_id HAVING avg(score)>80
    )
    Copy after login

    Query the records of a student who failed in each subject

    ###查询一个学生每科分数不及格的记录
    SELECT
    	* 
    FROM
    	score 
    WHERE
    	student_id IN 
    	( SELECT student_id FROM score GROUP BY student_id HAVING max( score ) < 60 )
    Copy after login

    Attachment: sql inserted into table structure

    CREATE TABLE `score` (
      `id` int(11) NOT NULL AUTO_INCREMENT COMMENT &#39;主键&#39;,
      `subject` varchar(20) DEFAULT NULL COMMENT &#39;科目&#39;,
      `student_id` int(11) DEFAULT NULL COMMENT &#39;学生id&#39;,
      `student_name` varchar(20) NOT NULL COMMENT &#39;学生姓名&#39;,
      `score` double DEFAULT NULL COMMENT &#39;成绩&#39;,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
    
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (1, '语文', 1, '张三', 59);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (2, '数学', 1, '张三', 78);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (3, '英语', 1, '张三', 65);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (4, '语文', 2, '李四', 88);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (5, '数学', 2, '李四', 58);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (6, '英语', 2, '李四', 65);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (7, '语文', 3, '王五', 92);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (8, '数学', 3, '王五', 99);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (9, '英语', 3, '王五', 96);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (10, '语文', 4, '小张', 90);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (11, '数学', 4, '小张', 91);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (12, '英语', 4, '小张', 90);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (13, '语文', 5, '小华', 88);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (14, '数学', 5, '小华', 79);
    INSERT INTO `test`.`score`(`id`, `subject`, `student_id`, `student_name`, `score`) VALUES (15, '英语', 5, '小华', 77);
    Copy after login

    The above is the detailed content of Mysql implements how to write sql to obtain the top few in each group after distinguishing by group. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template