tblPerson
-----------------------
idPerson | idCategory |
----------------------+
01 | 03 |
02 | 02 |
03 | 03 |
04 | 01 |
05 | 01 |
06 | 01 |
---------+------------+
tblAbsent
----------------------+
idPerson | idSituation|
----------------------+
01 | 02 |
04 | 01 |
05 | 04 |
06 | 01 |
---------+------------+
我想创建第三张桌子
tblTotal
-------------------+--------+---------+
idCategory | total | absent | present |
-----------+-------+--------+---------+
01 | 03 | 03 | 00 |
02 | 01 | 00 | 01 |
03 | 02 | 01 | 01 |
-----------+-------+--------+---------+
答案 0 :(得分:2)
您可以按照以下方式使用某些内容:
select
q.idcategory,
q.total,
count(t.idcategory) as absent,
q.total-count(t.idcategory) as present
from
(
select t.idcategory, count(*) as total
from tblperson t
group by t.idcategory
) q
left join tblabsent t on q.idcategory = t.idcategory
group by
q.idcategory,
q.total
order by
q.idcategory
在这里,子查询返回一组不同的idcategory
值,以及每个类别中的记录总数。
此子查询随后left joined
到tblabsent
表,并使用count([field])
仅计入非空值(而count(*)
将计入全部记录)以返回缺少/存在的记录总数。
答案 1 :(得分:1)
您似乎在表之间具有简单的关系。我建议:
select p.idCategory,
count(*) as total,
count(a.idPerson) as absent,
(count(*) - count(a.idPerson)) as present
from tblPerson as p left join
tblAbsent as a
on p.idPerson = a.idPerson
group by p.idCategory;
不清楚为什么要在两个表之间重复idCategory
。
答案 2 :(得分:0)
select
q.idcategory,
q.total,
count(t.idcategory) as absent,
q.total-count(t.idcategory) as present
from
(
select t.idcategory, count(*) as total
from tblperson t
group by t.idcategory
) q
left join (select tblAbsent.idPerson as idPerson, tblPerson.idCategory as idCategory FROM tblPerson inner join tblAbsent on tblPerson.idPerson=tblAbsent.idPerson) t on q.idcategory = t.idcategory
group by
q.idcategory,
q.total
order by
q.idcategory