题
我有一个包含以下表格的查询(简化为仅显示感兴趣的列)。
t1
code
t2
code, period, status
t3
period, desc
现在我拥有的是,
t3是唯一的“句号”表。
t1是唯一代码表。
t2是将这两者连在一起的连接表,以及状态,为了这个例子,状态=(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
不隶属于 StackOverflow