簡體   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