带有count和left join的SQL查询

时间:2017-05-23 16:03:53

标签: sql sql-server count

我有一个查询,我需要从2个表中计算'userID'。

SQL QUERY:

    SELECT DISTINCT TOP 1000 u.id as userID, u.firstName as userFirstName, u.email as userEmail, u.phone as userPhone, 
count(ueo.userID) as opensEmailCounter, count(ush.userID) as opensSmsCounter
    FROM dbo.Users u
    LEFT JOIN dbo.UserEmailsOpens ueo ON u.id = ueo.userID AND ueo.targetID = 4
    LEFT JOIN dbo.UserSmsHistory ush ON u.id = ush.userID AND ush.targetID = 4 AND ush.opened = 1
    WHERE u.deleted = 0
    AND IsNull(u.firstName, '') != '' 
    AND IsNull(u.email, '') != '' 
    AND IsNull(u.phone, '') != ''
GROUP BY u.id, u.firstName, u.email, u.phone

但是,结果并不是我的预期。在我做了第二次左连接后,它给了我错误的数字。在某些情况下,它是我的结果的两倍,并显示相同的计数结果(附上截图)。 enter image description here

2 个答案:

答案 0 :(得分:1)

在加入之前聚合如下:

{{1}}

答案 1 :(得分:0)

稍微修改了你的查询。使用Case When来消除结果中空白的计数。

Select userID, userFirstName, userEmail, userPhone, 
sum(case when ueo_userID <> '' then 1 else 0 end) as opensEmailCounter,
sum(case when ush_userID <> '' then 1 else 0 end) as opensSmsCounter
from
 (
    SELECT DISTINCT u.id as userID, u.firstName as userFirstName, u.email as userEmail, u.phone as userPhone, 
    ueo.userID as ueo_userID, ush.userID as ush_userID
    FROM dbo.Users u
    LEFT JOIN dbo.UserEmailsOpens ueo ON u.id = ueo.userID AND ueo.targetID = 4
    LEFT JOIN dbo.UserSmsHistory ush ON u.id = ush.userID AND ush.targetID = 4 AND ush.opened = 1
    WHERE u.deleted = 0user
    AND IsNull(u.firstName, '') != '' 
    AND IsNull(u.email, '') != '' 
    AND IsNull(u.phone, '') != ''
 ) a
GROUP BY userID, userFirstName, userEmail, userPhone;

如果您有任何问题,请告诉我