[英]How to insert values into a table from two tables?
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 |
-----------+-------+--------+---------+
您可能会使用以下内容:
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(*)
将计算所有记录)的事实返回缺失/存在记录的总数.
您似乎在表之间具有简单的关系。 我会建议:
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
。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.