简体   繁体   English

来自带有条件的许多INNER JOIN表的多个计数

[英]Multiple Counts from many INNER JOIN tables with Conditions

I'm having a lot of trouble figuring out how to write this query. 我在弄清楚如何编写此查询时遇到很多麻烦。 Here's an exmaple of the data set and what I need to query: 这是数据集和我需要查询的示例:

**System Table**    

SystemID   Active
1          T
2          T
3          T
4          F
5          F
6          F

**BlogPost Table**      

BlogPostID  SystemID    Create_Month
100         2           Jan
101         2           Jan
102         2           Feb
103         3           Feb
104         3           Mar
105         6           Mar
106         6           Mar

**Comment Table**       

Comment ID  BlogPostID  Liked
201         100         T
202         100         T
203         100         T
204         102         T
205         102         T
206         102         T
207         103         F

So, In words, I'm trying to get: By month, show me all the active systems who created a post during that month, the number of posts they made in aggregate, and the count of the subset of those posts who had a comment that was like. 因此,我想尝试得到:按月显示,显示该月内创建帖子的所有活动系统,它们合计发布的帖子数量以及这些帖子的子集数评论就像。

The end result would be like: 最终结果将是:

Column 1 - Month

Column 2 - Count of Active Systems where a Post Created in Month

Column 3 - Count of Posts Applicable to those systems

Column 4 - Count of Applicable Posts that had comments that were liked  

I don't even know where to start really. 我什至不知道真正从哪里开始。 My terrible "this is obviously wrong" attempt is below. 我可怕的“这显然是错误的”尝试如下。 Any help is much appreciated, thanks! 非常感谢任何帮助,谢谢!

SELECT
  Month, 
  COUNT(DISTINCT system.systemid), 
  COUNT(blogpost.BlogPostID)
  COUNT(comments.commentiD)
FROM
  system INNER JOIN
  blogpost ON system.systemid = blogpost.systemid INNER JOIN
  comments ON blogpost.BlogPostID = comment.BlogPostID
WHERE
  system.active = T 
  AND comments.like = T
GROUP BY month

A complicated one ! 一个复杂的!

SELECT 
b.Create_Month, 
COUNT(DISTINCT s.SystemID) as SystemCount, 
COUNT(DISTINCT b.BlogPostID) as PostsCount,
COUNT(DISTINCT t.BlogPostID) as PostsWithLike

FROM System s 

JOIN BlogPost b 
ON s.systemID = b.systemID 
AND s.Active = 'T'  

LEFT JOIN Comment c 
ON b.BlogPostID = c.BlogPostID

LEFT JOIN
(
SELECT DISTINCT c.BlogPostID as BlogPostID
FROM 
Comment c 
GROUP BY c.BlogPostID 
HAVING SUM(if(c.Liked='T',1,0))>0
) as t
ON b.BlogPostID = t.BlogPostID

GROUP BY b.Create_Month 

This is probably what you want : 这可能是您想要的:

SELECT s.systemid, active, bp.create_month, bp.systemid, COUNT(bp.blogpostid), COUNT(c.liked)
FROM system AS s 
     LEFT OUTER JOIN Blogpost AS bp ON s.systemid = bp.systemid 
     LEFT OUTER JOIN Comment AS c ON bp.blogpostid = c.blogpostid 
WHERE active = 'T' AND c.Liked = 'T' GROUP BY s.systemid,bp.create_month

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM