你可以试试这样的:
数据准备
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 是存在百分比。请注意,John 和 Matt 的出席率分别为 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;
出席百分比将是学生出席的次数除以总数。所以,这就是我在子查询中所做的。
一旦有关学生的数据可用,将该结果与学生的信息相结合,并从两个表中提取所需的信息。