从先前的聚合值中获取另一个聚合值

Getting another aggregate value from a previously aggregated value

如果我有这样的 Sql 查询:

select 
    ..., count(t2.value) as t2_count, count(t3.value) as t3_count
from 
    table t1
left join
    table2 t2
on
    t2.id = t1.id
left join
    table3 t3
on
    t3.id = t1.id
group by
    t1.id
order by
    t1.id;

这将导致 table 像这样:

|... | ... | t2_count | t3_count
------------------------------------
|... | ... | 3        | 4
|... | ... | 3        | 3 

现在我只是在 Postgres 中使用计数聚合,我想要实现的是另一个使用 t2_count 和 t3_count 的值作为参数的聚合列。专门检查它们是否匹配:

|... | ... | t2_count | t3_count | (aggregate, match?)
-----------------------------------------
|... | ... | 3        | 4        | false
|... | ... | 3        | 3        | true

如何在 Postgresql 中执行此操作?谢谢!

我认为您不需要另一个聚合来实现您想要的。您可以使用简单的 CASE 表达式:

select 
    ..., count(t2.value) as t2_count, 
         count(t3.value) as t3_count,
    CASE WHEN count(t2.value) =  count(t3.value) THEN 'True'
         ELSE 'false'
    END AS "Match"
from 
    table t1
left join
    table2 t2
on
    t2.id = t1.id
left join
    table3 t3
on
    t3.id = t1.id
group by
    t1.id
order by
    t1.id;