sql查询每科成绩的最高分_MYSQL查询每科前三名的成绩

91e2cac241b0e7738dc45b71736cd398.png

1.创建总表score;

mysql> use test;

Database changed

mysql> CREATE TABLE score (

-> id int(10) NOT NULL AUTO_INCREMENT,

-> subject_id int(10) DEFAULT NULL,

-> student_id int(10) DEFAULT NULL,

-> score float DEFAULT NULL,

-> PRIMARY KEY (id)

-> ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

Query OK, 0 rows affected, 4 warnings (0.61 sec)

93198ef8f7f68be5dd67c1a10ec21324.png

2.输入表中内容;

mysql> INSERT INTO SCORE VALUES(1,1,1,96),(2,1,2,86),(3,1,3,99),(4,1,4,78),(5,1,5,89);

Query OK, 5 rows affected (0.43 sec)

Records: 5 Duplicates: 0 Warnings: 0

mysql> INSERT INTO SCORE VALUES(6,2,1,97),(7,2,2,88),(8,2,3,98),(9,2,4,79),(10,2,5,87);

Query OK, 5 rows affected (0.04 sec)

Records: 5 Duplicates: 0 Warnings: 0

mysql> INSERT INTO SCORE VALUES(11,3,1,99),(12,3,2,87),(13,3,3,97),(14,3,4,77),(15,3,5,88);

Query OK, 5 rows affected (0.12 sec)

Records: 5 Duplicates: 0 Warnings: 0

e83007e7363b0524203c44812b1d6c65.png

3.输入具体的表内容;

mysql> CREATE TABLE student (

-> id int(10) NOT NULL AUTO_INCREMENT,

-> name varchar(10) DEFAULT NULL,

-> PRIMARY KEY (id)

-> ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

Query OK, 0 rows affected, 2 warnings (0.30 sec)

3b11931e288781dd58250063109aee20.png

INSERT INTO STUDENT VALUES(1,'张斌'),(2,'李四'),(3,'王五'),(4,'周六'),(5,'张三');

Query OK, 5 rows affected (0.72 sec)

Records: 5 Duplicates: 0 Warnings: 0

11700da7d0737a34957b21a113ce8a37.png

INSERT INTO SUBJECT VALUES(1,'java'),(2,'c++'),(3,'python');

Query OK, 3 rows affected (0.53 sec)

Records: 3 Duplicates: 0 Warnings: 0

2e399f4b440ceb31ba9b9984b979fb39.png

4.查询

select a.id,a.subject_id,a.student_id,a.score from score as a left join score as b on a.subject_id=b.subject_id and a.score>=b.score

group by a.subject_id,a.student_id,a.score

having count(a.subject_id)>=3

order by a.subject_id,a.score desc;

+----+------------+------------+-------+

| id | subject_id | student_id | score |

+----+------------+------------+-------+

| 3 | 1 | 3 | 99 |

| 1 | 1 | 1 | 96 |

| 5 | 1 | 5 | 89 |

| 8 | 2 | 3 | 98 |

| 6 | 2 | 1 | 97 |

| 7 | 2 | 2 | 88 |

| 11 | 3 | 1 | 99 |

| 13 | 3 | 3 | 97 |

| 15 | 3 | 5 | 88 |

+----+------------+------------+-------+

9 rows in set (0.00 sec) #这里把所有的列都列出来了便于对比 这里把表score的每一条同subject_id的数据都连接起来

a0290320cc902caf0d61bab037cc11d2.png

#按subject_id,student_id,score来进行分组; #添加count(a.subject_id)来进行对比易于理解

分组后再进行条件查询;

接下来就是排序:

baa64531c60c88e70a33a819ac0d8361.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值