如何从两个表向表中插入值?

时间:2019-12-27 21:26:12

标签: sql ms-access

  • 使用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总计,tblAbsent.COUNT(idCategory),AS缺少,总的AS缺失)
tblTotal
-------------------+--------+---------+
idCategory | total | absent | present |
-----------+-------+--------+---------+
01         |  03   |   03   |   00    |
02         |  01   |   00   |   01    |
03         |  02   |   01   |   01    |
-----------+-------+--------+---------+

3 个答案:

答案 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 joinedtblabsent表,并使用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