我有一个包含下表的查询(简化为仅显示感兴趣的列)。
t1
code
t2
code, period, status
t3
period, desc
现在我所拥有的是,
t3 是一个包含唯一“周期”的表。
t1 是唯一代码表。
t2 是将两者链接在一起的连接表以及状态,在本示例中 status=(A,B,C)。
我正在做的是创建一个按“句点”分组的查询结果,并包含每个状态中的“代码”计数。
这很容易解决,但我想将其扩展到,不仅要计算 A、B 和 C 中的“代码”数量,还要计算与句点或不相关的代码的数量换句话说,是给定时间段内不在 t2 中的代码计数。
所以我正在寻找的结果是
Period A B C (Codes from t1 not found in t2)
P1 10 5 2 3
P2 5 5 5 10
最佳答案
您可以使用交叉连接来选择所有期间的所有代码的矩阵。这允许您计算不存在的行:
select
sum(case when t2.status is 'A' then 1 else 0 end) as ACount,
sum(case when t2.status is 'B' then 1 else 0 end) as BCount,
...
sum(case when t2.code is null then 1 else 0 end) as NotPresentCount
from t1
cross join t3
left join t2
on t2.code = t1.code and t2.period = t3.period
group by t3.period
关于sql - mysql连接查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1801590/