统计学生成绩的SQL

现在有一个表:
成绩表
t_result:

    a_no      a_type      a_subject      a_flag
    001        0000            A            1
    001        0000            B            1
    001        0001            A            1
    001        0001            C            0
    002        0000            C            1
    002        0000            E            0
    002        0000            F            1
    002        0001            A            1
    002        0001            B            0
    002        0001            C            1

有自己的编号(a_no),还有一个类型编号(a_type), 这两个字段作为表的主键。
可以选不同可的科目,且科目的数量及个数都可以不同。后面是标识当前科目是否通过。
现在想做一个统计语句,求出的结果类似于查出来按照主键进行分组。

查询的结果实例为:
    a_no      a_type        全部通过
    001        0000              Y
    001        0001              N
    002        0000              N
    002        0001              N

 

SQL代码如下:

 

简练版本

 

### SQL按分统计学生成绩分布 为了实现按照指定分段(90-100,80-89,70-79,60-69,<60)统计学生成绩分布的情况,可以采用 `CASE WHEN` 的方法来定义各个分段,并通过聚合函 `SUM()` 来计算每个分段的人。以下是具体的解决方案: #### 创建并插入据 首先,假设有一个成绩 `student_scores`,其结构如下: ```sql create table student_scores ( sid varchar(10), -- 学生ID name varchar(50), -- 学生姓名 score int -- 成绩 ); ``` 接着向该中插入一些测试据: ```sql insert into student_scores(sid, name, score) values ('S001', 'Alice', 92), ('S002', 'Bob', 85), ('S003', 'Charlie', 78), ('S004', 'David', 65), ('S005', 'Eve', 58), ('S006', 'Frank', 95), ('S007', 'Grace', 88), ('S008', 'Heidi', 72), ('S009', 'Ivan', 67), ('S010', 'Judy', 55); ``` #### 编写SQL查询语句 下面是一个完整的SQL查询语句,用于统计各分段的学生: ```sql select count(case when score >= 90 and score <= 100 then 1 else null end) as "90-100", count(case when score >= 80 and score <= 89 then 1 else null end) as "80-89", count(case when score >= 70 and score <= 79 then 1 else null end) as "70-79", count(case when score >= 60 and score <= 69 then 1 else null end) as "60-69", count(case when score < 60 then 1 else null end) as "<60" from student_scores; ``` 此查询的核心在于使用 `COUNT(CASE WHEN ...)` 构造条件达式[^1],分别针对不同的分区间进行判断和计。 #### 查询结果解释 执行以上SQL语句后,会得到类似以下的结果格: | 90-100 | 80-89 | 70-79 | 60-69 | <60 | |--------|-------|-------|-------|-----| | 2 | 2 | 2 | 2 | 2 | 每一列代对应分区间的总人。 --- ### 注意事项 如果需要进一步扩展功能,比如按班级或其他维度分组统计,则可以在原有基础上增加 `GROUP BY` 子句。例如,若要按学生所属班级分类统计,可修改为以下形式: ```sql select class, count(case when score >= 90 and score <= 100 then 1 else null end) as "90-100", count(case when score >= 80 and score <= 89 then 1 else null end) as "80-89", count(case when score >= 70 and score <= 79 then 1 else null end) as "70-79", count(case when score >= 60 and score <= 69 then 1 else null end) as "60-69", count(case when score < 60 then 1 else null end) as "<60" from student_scores group by class; ``` 这将返回每班学生成绩分布情况[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值