MySQL sum, count with group by and joins

Viewed 1763

I have three tables types, post and insights.

  • Types table contains the types of post.
  • post table contains the post that have been made.
  • the insight table contains the insights of post on daily basis.

Here is the link to my sql fiddle SQL Fiddle.

Now i want to generate a report which contains number of post against each type and the sum of their likes and comments i.e. Type | COUNT(post_id) | SUM(likes) | SUM(comments).

These are my tries:

select type_name, count(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;

Result: Aggregate values are not correct.

select type_name, count(p.post_id), p.post_id, 
  (select sum(likes) from insights where post_id = p.post_id) as likes, 
  (select sum(comments)from insights where post_id = p.post_id) as comments
from types t
left join posts p on t.type_id = p.post_type
group by type_name;

Result: Displays the sum of likes and comments of only one post.

2 Answers
Related