如果我有这样的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;
这将产生如下表:
|... | ... | t2_count | t3_count
------------------------------------
|... | ... | 3 | 4
|... | ... | 3 | 3
现在我只是在Postgres中使用count聚合,我想要实现的是使用t2_count和t3_count的值作为参数的另一个聚合列。具体来检查它们是否匹配如下:
|... | ... | t2_count | t3_count | (aggregate, match?)
-----------------------------------------
|... | ... | 3 | 4 | false
|... | ... | 3 | 3 | true
如何在Postgresql中执行此操作?谢谢!
答案 0 :(得分:1)
我认为你不需要另一个聚合来实现你想要的东西。您可以使用简单的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;