mysql - 在mysql中计算出勤率时出现语法错误
问题描述
SELECT name, DISTINCT studentid, count(attendance)
from attendance a,students s
where attendance = 'p'and s.studentid=a.studentid
having count(attendance)<3/4*sum(attendance);
我有 2 个表出勤率和学生,我想从中选择学生的姓名(来自学生表)和出勤率(来自出勤表),其中 studentid 是那些出勤率<75% 的学生的外键。我将出席情况分别保存为 p 和 a 代表出席和缺席。
解决方案
你可以尝试这样的事情:
数据准备
create table attendance (studentid int, attendance char(1));
insert into attendance values (1,'p'),(1,'a'),(2,'p'),(2,'p'),(2,'a'),(3,'p');
数据
select * from students;
+-----------+------+
| studentid | name |
+-----------+------+
| 1 | John |
| 2 | Matt |
| 3 | Mary |
+-----------+------+
select * from attendance;
+-----------+------------+
| studentid | attendance |
+-----------+------------+
| 1 | p |
| 1 | a |
| 2 | p |
| 2 | p |
| 2 | a |
| 3 | p |
+-----------+------------+
询问
select s.*, a.total, a.p_present
from students s
inner join (
select studentid, count(*) as total, sum(case attendance when 'p' then 1 else 0 end) * 100/count(*) as p_present
from attendance
group by studentid
) a on s.studentid = a.studentid
where a.p_present < 75 ;
结果
+-----------+------+-------+-----------+
| studentid | name | total | p_present |
+-----------+------+-------+-----------+
| 1 | John | 2 | 50.0000 |
| 2 | Matt | 3 | 66.6667 |
+-----------+------+-------+-----------+
p_present 是存在百分比。请注意,约翰和马特的出席率分别为 50% 和 66.6%。
解释
为了获得总记录,我们会做这样的事情:
select studentid, count(*)
from attendance
group by studentid;
为了获得每个学生在场的总时间,我们会这样做:
select studentid, sum(case attendance when 'p' then 1 else 0 end)
from attendance
group by studentid;
出席百分比将是学生出席的次数除以总数。所以,这就是我在子查询中所做的。
一旦有关学生的数据可用,将该结果与学生的信息连接起来,并从两个表中提取所需的信息。
推荐阅读
- sql - SQL 服务器问题 - Create Function 必须是批处理中的唯一语句
- r - R stats::aggregate() 的“找不到对象”错误:两个相似的测试结果不同?
- git - 断言当前 HEAD 指向 master 的命令?
- git - 为什么我不能 git 捆绑所有父母?
- animation - 最简单的动画会导致高 CPU 使用率和非常高的能量影响 SpriteKit
- android - 如何在 BIOS 中为 x86 windows 启用 VT-x 以运行模拟器
- linux - 如何在 Linux 中的 C++ 中获取 Raspberry Pi 板上第二个 SD 卡插入/移除的事件
- css - SVG 相互覆盖 CSS 样式
- php - 在 get_instance 期间,Codeigniter 上的多个数据库在自定义库上未按预期工作
- swift - 将 Date 设置为 DatePicker 和侦听器以更改值和删除 AR 前缀