3

我有以下 SQL:

SELECT 
    ud.firstname + ' ' + ud.lastname, 
    COUNT(a.createdDate) AS ActivityCount, 
    au.LastActivityDate
FROM 
    dbo.aspnet_Users au 
    INNER JOIN dbo.UserDetails ud 
    ON au.UserId = ud.AspNetUserId
    LEFT OUTER JOIN dbo.audit a 
    ON au.LoweredUserName = a.username
WHERE 
    (
        au.LoweredUserName IN ('u1', 'u2', 'u3')
    ) 
AND a.createdDate > '2012-09-18'
GROUP BY ud.firstname + ' ' + ud.lastname, au.LastActivityDate
ORDER BY au.LastActivityDate DESC

但是让我们说,u1并且u3没有任何活动,因为2012-09-18-- 那么结果只包含u2.

我认为LEFT OUTER JOIN确保我从中获取所有记录aspnet_Users- 但我想这是由于我的WHERE子句中的秒条件过滤另一个表......

为了获得所有指定的用户,我需要更改什么,然后如果在给定期间不存在数据,则 ActivityCount 为零?

4

2 回答 2

4

但我想这是由于我的 WHERE 子句中的秒条件过滤了另一个表......

对,createdDateinWHERE子句的条件是抑制来自dbo.audit. 您可以将其移至LEFT OUTER JOIN条件列表以获得所需的结果。

于 2012-09-19T09:33:45.377 回答
0
SELECT 
    ud.firstname + ' ' + ud.lastname,
    sum(case when a.createdDate is null then 0 else 1 end) AS ActivityCount, 
    au.LastActivityDate
FROM 
    dbo.aspnet_Users au 
    INNER JOIN dbo.UserDetails ud 
    ON au.UserId = ud.AspNetUserId
    LEFT OUTER JOIN dbo.audit a 
    ON au.LoweredUserName = a.username
WHERE 
    (au.LoweredUserName IN ('u1', 'u2', 'u3')) 
AND (a.createdDate > '2012-09-18' or a.createdDate is null)
GROUP BY 
    ud.firstname + ' ' + ud.lastname,
    au.LastActivityDate
ORDER BY au.LastActivityDate DESC
于 2012-09-19T09:31:06.820 回答