MySQL sum, count with group by and joins

痴心易碎 提交于 2019-11-27 08:05:50

问题


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.


回答1:


Your first attempt was real close. But each post_id was being multiplied by the number of matches in insights, so you need to use 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;

Alternatively, you can group with a subquery that combines all the insights for the same post:

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;

FIDDLE




回答2:


try this

SELECT types.type_name, stats.posts, stats.likes, stats.comments
FROM types
LEFT JOIN (
select post_type, count(i.post_id) as posts, sum(i.likes) as likes, sum(i.comments) as comments
from insights i INNER JOIN posts p ON i.post_id = p.post_id
) as stats
ON types.type_id = stats.post_type;


来源:https://stackoverflow.com/questions/20756948/mysql-sum-count-with-group-by-and-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!