我有这两张桌子:
瞳孔:
id_pupil
name
surname
email
user
pass
level
class
事件:
id_incidents
date
time
type_incident(miss, delay or attitude)
comments
id_pupil
id_user
subject
id_trimester
我想得到这个:
我写这个:
select pupils.id_pupil, name, surname, count(type_incident) as misses
from pupils left join incidents using (id_pupil)
where type_incident='miss' and level=1 and class='B' and id_trimester=1
group by id_pupil
我得到了每个学生未命中的专栏。但是,我没有得到空值,因为我想得到0个未命中的学生。
同样的延迟和态度:
select pupils.id_pupil, name, surname, count(type_incident) as misses
from pupils left join incidents using (id_pupil)
where type_incident='delay' and level=1 and class='B' and id_trimester=1
group by id_pupil
select pupils.id_pupil, name, surname, count(type_incident) as misses
from pupils left join incidents using (id_pupil)
where type_incident='attitude' and level=1 and class='B' and id_trimester=1
group by id_pupil
我希望所有人都在图片中描述的同一张表中。
谢谢!
答案 0 :(得分:1)
我认为juergen的答案会比我的更好,因为代码更具可读性,但由于我已经输入了我的内容,我会继续发布另一种方法来实现相同的结果:我原来的两个建议是添加{ {1}}和name
到您的GROUP BY语句;另外,将条件surname
从WHERE上移到你的LEFT JOIN中,如下所示:
and id_trimester=1
答案 1 :(得分:0)
将条件放在sum()
中。它总结了您的条件成立的次数(1
)
select pupils.id_pupil, name, surname,
sum(type_incident='miss' and level=1 and class='B' and id_trimester=1) as misses,
sum(type_incident='delay' and level=1 and class='B' and id_trimester=1) as delays,
sum(type_incident='attitude' and level=1 and class='B' and id_trimester=1) as attitudes
from pupils
left join incidents using (id_pupil)
group by id_pupil, name, surname
答案 2 :(得分:0)
SELECT CONCAT(p.name, ' ', p.surname) AS Pupil, t1.misses, t2.delays, t3.attitude
FROM pupils AS p
LEFT JOIN (SELECT COUNT(*) AS misses FROM id_incidents WHERE type_incident = 'miss' and level=1 and class='B' and id_trimester=1) AS t1 ON (t1.id_user = p.id_pupil)
LEFT JOIN (SELECT COUNT(*) AS delays FROM id_incidents WHERE type_incident = 'delay' and level=1 and class='B' and id_trimester=1) AS t2 ON (t2.id_user = p.id_pupil)
LEFT JOIN (SELECT COUNT(*) AS attitude FROM id_incidents WHERE type_incident = 'attitude' and level=1 and class='B' and id_trimester=1) AS t3 ON (t3.id_user = p.id_pupil)