Sql多级聚合

时间:2017-12-13 07:26:39

标签: sql sql-server sql-server-2008

我有这个数据库图表:

enter image description here

考虑到图中的关系,我想计算每个 RoomType 的LikesCount之和,计算的数量总和将计算如下:

RoomTypeLikesCount = Sum(Replays.LikesCount) + 
                     Sum(Comments.LikesCount) + 
                     Sum(Posts.LikesCount)

根据图中的关系作为非重复计数。

我想知道是否有任何简单的高性能方式。

[更新]

注意:我想排除已归档或已阻止的记录,只考虑isVisible = true的房间。

我的尝试是:

--get comment replays likes, dislikes counts [SUM]
SELECT 
    C.PostID, C.CommentID, 
    ISNULL(COUNT(RP.ReplayID), 0) ReplayCount,
    ISNULL(C.LikesCount, 0) + ISNULL(SUM(RP.LikesCount), 0) LikesCount,
    ISNULL(C.DislikesCount, 0) + ISNULL(SUM(RP.DislikesCount), 0) DislikesCount
INTO 
    #CommentStats
FROM  
    CollaborationDB.DiscussionRooms.Comments C 
LEFT JOIN 
    DiscussionRooms.Replays RP ON RP.CommentID = C.CommentID 
                               AND RP.IsBlocked = 0 
                               AND RP.IsArchived = 0
WHERE 
    c.IsBlocked = 0 
    AND C.IsArchived = 0
GROUP BY 
    C.PostID, C.CommentID, C.LikesCount, C.DislikesCount

--get posts views, likes, dislikes counts 
SELECT 
    P.RoomID, P.PostID, P.ViewsCount,
    ISNULL(COUNT(CS.CommentID), 0) + ISNULL(SUM(ReplayCount), 0) CommentCount,
    ISNULL(P.LikesCount, 0) + ISNULL(SUM(CS.LikesCount), 0) LikesCount,
    ISNULL(P.DislikesCount, 0) + ISNULL(SUM(CS.DislikesCount), 0) DislikesCount
INTO 
    #PostStats
FROM  
    CollaborationDB.DiscussionRooms.Posts P
LEFT JOIN 
    #CommentStats CS ON CS.PostID = P.PostID
                     AND P.IsBlocked = 0 
                     AND P.IsArchived = 0
GROUP BY 
    P.RoomID, P.PostID, P.ViewsCount, P.LikesCount, P.DislikesCount

--get Room Types Rooms, Posts, views, likes, dislikes counts 
SELECT 
    RT.TypeName,
    ISNULL(COUNT(DISTINCT R.RoomID), 0) [RoomsCount],
    ISNULL(COUNT(DISTINCT PS.PostID), 0) [PostsCount],
    ISNULL(SUM(PS.LikesCount), 0) LikesCount,
    ISNULL(SUM(PS.DislikesCount), 0) DislikesCount,
    ISNULL(SUM(PS.ViewsCount), 0) ViewsCount
FROM 
    CollaborationDB.DiscussionRooms.RoomTypes RT
LEFT JOIN 
    CollaborationDB.DiscussionRooms.Rooms R ON R.RoomTypeID = RT.RoomTypeID 
                                            AND R.IsVisible = 1 
                                            AND R.IsArchived = 0
LEFT JOIN 
    #PostStats PS ON PS.RoomID = R.RoomID
WHERE 
    rt.IsArchived = 0 
    AND R.IsVisible = 1 
    AND R.IsArchived = 0
GROUP BY 
    RT.RoomTypeID, RT.TypeName

0 个答案:

没有答案