在连接结果

时间:2018-03-28 09:44:42

标签: sql sql-server

我有一个用户和一个活动表。用户获得他们活动的积分,我希望在特定时间段内按积分获得前5名用户的列表:

select top 5 [firstname], [lastname], SUM(user_activities.duration) as points
from      [users]
left join [user_activities] on [users].[id] = [user_activities].[user_id] 
WHERE     [user_activities].[timestamp] >= '2018-03-01'
and       [user_activities].[timestamp] <= '2018-03-31'
group by [firstname], [lastname]
order by [points] desc, [firstname] asc

不幸的是没有活动的用户不会出现。这是因为timestamp子句的位置。有没有办法将它们包括在内?他们只有0分。

2 个答案:

答案 0 :(得分:1)

将WHERE子句移动到JOIN

SELECT TOP 5
            firstname
            , lastname
        , SUM(ISNULL(user_activities.duration,0)) AS points
FROM
            users
LEFT JOIN   user_activities ON  users.id = user_activities.user_id
                            AND user_activities.timestamp   >= '2018-03-01'
                            AND user_activities.timestamp   <= '2018-03-31'
GROUP BY
            firstname
            , lastname
ORDER BY
            points DESC
            , firstname ASC;

答案 1 :(得分:1)

WHERE切换为AND。 (现在您的left join会返回inner join结果。)

即。右边的表条件应该在ON子句中!

select top 5 [firstname], [lastname], SUM(user_activities.duration) as points
from [users] left join [user_activities] on [users].[id] = [user_activities].[user_id] 
  and [user_activities].[timestamp] >= '2018-03-01'
  and [user_activities].[timestamp] <= '2018-03-31'
group by [firstname], [lastname]
order by [points] desc, [firstname] asc