使用MS Office 2019,我有2张桌子:
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 |
---------+-------------+
我要创建第三个表,其中包含:
总计
SELECT COUNT(*) FROM tblPerson
WHERE idCategory=x
第1列
SELECT COUNT(*) FROM tblAbsent
WHERE (idSituation=1 OR idSituation=2)
AND idCategory=x
第2列
SELECT COUNT(*) FROM tblAbsent
WHERE (idSituation=3 OR idSituation=4)
AND idCategory=x
x = {01,02,03}
tblTotal
-----------+-------+---------+--------+------------------------+
idCategory | total | column1 | column2| total-(column1+column2)|
-----------+-------+---------+--------+------------------------+
01 | 03 | 02 | 01 | 00 |
02 | 01 | 00 | 00 | 01 |
03 | 02 | 01 | 00 | 01 |
-----------+-------+---------+--------+------------------------+
答案 0 :(得分:0)
加入表,按idCategory分组并使用条件聚合:
SELECT p.idCategory,
COUNT(*) AS total,
SUM(IIF(a.idSituation IN (1, 2), 1, 0)) AS column1,
SUM(IIF(a.idSituation IN (3, 4), 1, 0)) AS column2,
(total - (column1 + column2)) AS column3
FROM tblPerson p LEFT JOIN tblAbsent a
ON a.idPerson = p.idPerson
GROUP BY p.idCategory