0

我们有一个允许用户创建自己的组的工具。在这些组中,用户可以写帖子。我要确定的是组大小与该组中帖子总数之间的关系。

我可以执行 SQL 语句来获取组名列表和该组中的用户数(查询 1)以及组名列表和帖子数(查询 2),但我希望两者都在同一个询问。

查询 1

select count(pg.personID) as GroupSize, g.GroupName
from Group g inner join PersonGroup pg g.GroupID = pg.GroupID
where LastViewed between @startDate and @enddate and
    g.Type = 0
group by g.GroupID, g.GroupName
order by GroupSize

查询 2

select count(gp.PostID) as TotalPosts, g.GroupName
from Group g inner join GroupPost gp on g.GroupID = gp.GroupID
    inner join Post p on gp.PostID = p.PostID
where g.Type = 0 and
    gp.Created between @startDate and @enddate
group by g.GroupID, g.GroupName
order by TotalPosts

**注意:一个人可以将同一个“帖子”发布到多个群组

我相信从这些数据中我可以建立一个直方图(10-20 个用户、21-30 个用户等的组数),并在这些不同的 bin 中合并组的平均帖子数。

4

2 回答 2

2

一个简单的解决方案是将这些查询用作子查询,并将它们组合起来:

SELECT 
    grps.GroupName,
    grps.GroupSize,
    psts.TotalPosts
FROM (
    select count(pg.personID) as GroupSize, g.GroupName, g.GroupID
    from Group g inner join PersonGroup pg g.GroupID = pg.GroupID
    where LastViewed between @startDate and @enddate and
        g.Type = 0
    group by g.GroupID, g.GroupName
    order by GroupSize) grps
JOIN (
    select count(gp.PostID) as TotalPosts, g.GroupName, g.groupID
    from Group g inner join GroupPost gp on g.GroupID = gp.GroupID
        inner join Post p on gp.PostID = p.PostID
    where g.Type = 0 and
        gp.Created between @startDate and @enddate
    group by g.GroupID, g.GroupName
    order by TotalPosts) psts
ON psts.GroupID = grps.GroupID
于 2012-05-07T15:06:07.853 回答
0

Paul 的解决方案假定两组组(按帖子和按用户)是相同的。这可能不是真的,因此需要完整的外部连接或联合全部。

我的偏好如下:

with groups as 
(
   select *
   from Group g
   where g.Type = 0 
     and g.LastViewed between @startDate and @enddate
)
select GroupId, GroupName, SUM(GroupSize) as GroupSize, SUM(TotalPosts) as TotalPosts)
from 
(
  (select groups.GroupId, groups.GroupName, 1 as GroupSize, 0 as TotalPosts
   from groups 
   join PersonGroup pg 
     on pg.GroupId = groups.groupId
   ) 
   union all
   (select groups.GroupId, groups.GroupName, 0 as GroupSize, 1 as TotalPosts
    from groups 
    join GroupPost gp
      on groups.GroupId = gp.GroupId 
    join Post p
      on gp.PostId = p.PostId
    )
)
group by GroupId, GroupName

“with”子句定义了您正在使用的组集。这将定义放在一个地方,很明显两个子查询具有相同的过滤。这两个子查询仅具有指示两个变量中的每一个的标志,然后在更高级别进行聚合。有时在子查询中进行聚合会更有效,尤其是在有索引的情况下。

于 2012-05-07T19:42:49.877 回答