繁体   English   中英

如何将两个表中的值插入到一个表中?

[英]How to insert values into a table from two tables?

  • 使用 MS Office 2019
  • 我在一个协会中有特定数量的成员,每个成员都包含在一个特定的类别中。 我想制作一个表格,统计每个类别中存在和缺席的成员以及协会的总数。 ——
  • tblPerson (idPerson , idCategory)
  • tblAbsent ( idPerson , idSituation )
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 , tblPerson.COUNT(idCategory) AS total , tblAbsent.COUNT(idCategory) AS 不存在,total-absent AS 存在)
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 joinedtblabsent表,并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM