mysql中考勤%计算语法错误

bqf10yzr  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(288)
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);

我有两个表出勤和学生,我想从中选择学生的名字(从学生表)和出勤(从出勤表),其中studentid是出勤率<75%的学生的外键。我将出席人数分别保存为p和a表示出席和缺席。

hgb9j2n6

hgb9j2n61#

你可以这样做:
数据准备

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\ U present是百分比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;

%现在是学生在场的次数除以总数。所以,这就是我在子查询中所做的。
一旦学生的数据可用,将结果与学生的信息连接起来,并从两个表中提取所需的信息。

相关问题