合并具有不同WHERE条件的不同表中的count(*)

时间:2011-11-14 21:55:10

标签: sql

我有三张桌子

OWNERS: pk name
POSTS: pk, post_date, owner_pk
REPLIES: pk,reply_date, post_pk,owner_pk,comment_count

在两个日期之间:date1和date2我想要一个结果:

所有者:姓名COUNT(帖子)SUM(comment_count)

我的问题是我无法理解如何编写单独的查询来分别对POSTS REPLIES表进行求和。

Ex:第1天一篇文章完成了2条评论。第2天一篇文章没有评论。回复表存储给定帖子/日的评论总数。

PostA     Day1
CommentA1 Day1 
CommentA2 Day1 
PostB     Day2
CommentA3 Day2
PostC     Day3

运行第1天的查询:

Owner:Name count(post) sum(comment_count)
OwnerName  1           2    

运行第2天的查询:

OwnerName  1         1     

运行第3天的查询:

OwnerName  1         0     

2 个答案:

答案 0 :(得分:3)

而不是SUM(),而不是COUNT(DISTINCT)

SELECT
    o.name,
    COUNT(DISTINCT p.pk) AS posts,
    COUNT(DISTINCT r.pk) AS replies
FROM
    owners o
    LEFT JOIN posts p ON p.owner_pk = o.pk AND p.post_date BETWEEN @date1 AND @date2
    LEFT JOIN replies r ON r.post_pk = p.pk AND r.post_date BETWEEN @date1 AND @date2
GROUP BY
    o.pk,
    o.name

答案 1 :(得分:1)

你可能需要在问题中提供更多细节,但我怀疑你是在追求这样的事情:

SELECT name, COUNT(posts.pk), COUNT(replies.pk)
  FROM owners, OUTER (posts, OUTER replies)
  WHERE owners.pk = posts.owner_pk
    AND posts.pk = replies.post_pk
    AND (posts.post_date BETWEEN ? AND ? OR replies.reply_date BETWEEN ? AND ?)
  GROUP BY name