Change thinking, work record

Make a little progress every day. Work records.
Today, I want to write a new SQL but I don’t know how to write. The
data structure is similar to the following]

成绩表
用户   |   成绩
张三1 |   A+
张三2 |   B
张三3 |   B- 
李四1 |   B
李四2 |   C
李四3 |   B 
......
班级表
班级 |  用户   | 类型
A班  | 张三1 | 优秀班级
B班  | 李四1 | 普通班级
.....

I have been thinking about how many people in class A are excellent classes below A-, and class B is how many people in ordinary classes have scores above B-. Because the results are not numbers, they can’t be compared. I have been doing it on the two tables. Compare and think, will it be better if you add an extra table

字典表
字段| code
C- | 0
C  | 1
B- | 2
B  | 3
A- | 4 
A+ | 5 
班级表
班级 | 成员   | 类型   | code 
A班  | 张三1 | 优秀班级 | 4
B班  | 李四1 | 普通班级 | 2
.....

Now you can directly correlate the three tables to find out the number of people in each class below the standard

select a.班级,count(case when a.code = 4 and a.code > c.code then 1  
					when a.code = 2 and a.code > c.code then 1 end) as num
from 班级表 a 
left join 成绩表 b on a.用户 = b.用户
left join 字典表 c on c.code = b.成绩
group by a.班级

In this way, you can group by class and query the number of data below the standard.

Guess you like

Origin blog.csdn.net/zhongzih/article/details/108059172