选择Count Outer Joins和WHERE

时间:2012-09-19 09:28:36

标签: sql sql-server

我有以下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

但是,假设u1u32012-09-18以来没有任何活动 - 那么结果只包含u2

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

如果获取所有指定的用户,我需要更改什么,如果给定时间段内没有数据,我需要将零作为ActivityCount?

2 个答案:

答案 0 :(得分:4)

  

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

是的,createdDate子句中WHERE的条件是禁止dbo.audit的记录。您可以将其移至LEFT OUTER JOIN条件列表以获得所需的结果。

答案 1 :(得分: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