Tu primer intento estuvo muy cerca. Pero cada post_id
se estaba multiplicando por el número de coincidencias en insights
, por lo que debe usar DISTINCT
:
select type_name, count(distinct p.post_id), sum(likes), sum(comments)
from types t
left join posts p on t.type_id = p.post_type
left join insights i on p.post_id = i.post_id
group by type_name;
Alternativamente, puede agrupar con una subconsulta que combina todas las ideas para la misma publicación:
select type_name, count(*), sum(likes), sum(comments)
from types t
left join posts p on t.type_id = p.post_type
left join (select post_id, sum(likes) likes, sum(comments) comments
from insights
group by post_id) i on p.post_id = i.post_id
group by type_name;