2012-05-07 84 views
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個用戶,等等),並且在這些不同的箱子中包含組的平均帖子數量。

回答

1

簡單的解決辦法是使用這些查詢作爲子查詢,並結合他們:

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 
0

保羅的解決方案假定兩組組(按員額和用戶)是一樣的。這可能不是真的,因此無論是全外連接還是全部連接都需要。

我的選擇是:

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 

「同向」條款定義中集集團所使用。這將定義放在一個地方,使得兩個子查詢具有相同的過濾效果。這兩個子查詢只是簡單地標記這兩個變量中的每一個,然後在較高級別進行彙總。有時候在子查詢中進行聚合也更有效率,特別是在有索引的時候。

+0

OP的查詢使用略有不同的過濾:第二個查詢中的'gp.Created @startDate和@ enddate'與第一個查詢的'LastViewed between @startDate和@ enddate'之間。 「LastViewed」是「Group」列也不是一個確定的事實。 (是的,OP應該更清楚一點,但我們不應該假設太多,如果我們。) –

+0

除此之外,我實際上同意你的方法。我可能會使用連接表中的實際ID和替代項的NULL,因此,我會計算COUNT而不是SUM,但基本上這與您的建議相同。 –

相關問題