2左连接放在一起乘以结果。但它不应该

时间:2016-10-24 04:56:43

标签: sql sql-server join left-join

我正在建立一个聊天网站并向观众展示聊天记录,我有3个下拉列表 - 体育(默认为所有体育),日/月/年,在线用户/总用户。

现在,如果默认选择所有体育项目并选择1个月和总用户数,则预期结果应为

我的查询是

SELECT DISTINCT roo.[Sports], 
                roo.[Name], 
                COUNT(DISTINCT chu.ChatUserLogId) AS TotalUsers, 
                COUNT(DISTINCT liu.[LoggedInUserID]) AS UserOnline

 FROM Room AS roo 

 LEFT JOIN LoggedInUser AS liu ON roo.RoomID = liu.RoomID 
 LEFT JOIN ChatUserLog  AS chu ON roo.RoomID = chu.RoomID 
               AND chu.LoggedInTime >= DATEADD(DAY,-30,GETDATE()) 

 GROUP BY roo.[Sports], roo.[Name]   
 ORDER BY TotalUsers DESC

有人建议用我的方法实际上是因为这两个连接而增加了行数。所以我需要先聚合,然后加入。

所以最后,我也尝试了这个查询

with agg_ChatUserLog as (select RoomId, count(*) as cnt_user_tot from ChatUserLog WHERE LoggedInTime >= DATEADD(DAY,-30,GETDATE()) group by RoomId),                                            

       agg_LoggedInUser as (select RoomId, count(*) as cnt_user_logged from LoggedInUser group by RoomId)

select Sports, Name, cnt_user_tot, cnt_user_logged from Room r 

       left outer join agg_ChatUserLog acu on acu.RoomId = r.RoomId 

       left outer join agg_LoggedInUser alu on alu.RoomId = r.RoomId;

但这也是结果的倍增。

我在哪里查询错误?提前致谢,祝你有个美好的一天。

示例数据是:

Chatroom name   Total Users   Online users               

Basketball
Roomname27          32              5
Roomname11          15              3
Roomname32           8              1 

Football
Roomname5           63              12
Roomname18          44               7
Roomname4           15               2

1 个答案:

答案 0 :(得分:0)

您可以尝试其他语法:

select Sports, 
    Name, 
    coalesce(
        ( 
            select count(distinct C.ChatUserLogId) 
            from ChatUserLog as C
            where C.RoomId = R.RoomId 
              and C.LoggedInTime >= DATEADD(DAY,-30,GETDATE()) 
        ), 
    0) AS TotalUsers,
    coalesce(
        (
            select count(distinct D.LoggedInUserID)
            from LoggedInUser as D
            where D.RoomId = R.RoomId 
        ),
    0) AS UserOnline
from Room R 

使用这种语法,您将永远不会有比房间号更多的结果。 但是你也有房间白痴观众