[英]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.