ISNULL(Count(x),0)在null时不返回0

时间:2014-01-22 18:35:04

标签: tsql coalesce isnull

我有以下代码:

SELECT     FirstName, LastName,
(SELECT ISNULL(COUNT(UP1.EmailAddress), 0) AS HasEmail 
     From dbo.UserProfiles AS UP1 
     WHERE (NOT (UP1.EmailAddress IS NULL)) AND (CreatedBy = dbo.UserProfiles.UserID)
     GROUP BY CreatedBy) AS EmailEnteredCount FROM dbo.UserProfiles WHERE (IsStaff = 1)

示例结果:

LastName EmailEnteredCount

bill NULL

Larson 51

Christie 30

parrish NULL

senac NULL

代码正确执行但有一个例外,它在没有找到记录时返回空值而不是预期的0.我也尝试使用coalesce无效。

更新: 这回归我想要完成的只需要一个更清洁的解决方案。我真的不认为我需要创建临时表来替换空值。

drop table #tt
                    select userid,firstname, lastname, 
                    (
                      SELECT     count(*) AS HasEmail
                      FROM         dbo.UserProfiles AS UP1
                      WHERE     (UP1.EmailAddress IS NOT NULL)AND (UP1.CreatedBy = UserProfiles.UserId) and (datecreated between @startdate and @enddate)
                      GROUP BY CreatedBy
                    ) as EmailCount
                    into #tt
                    from dbo.UserProfiles where isstaff = 1

                    select userid,firstname, lastname, ISNULL(EmailCount,0) As EmailCount from #tt

任何帮助都将不胜感激。

谢谢, 克里斯

2 个答案:

答案 0 :(得分:4)

您需要在相关子查询之外移动isnull函数,如下所示:

SELECT  FirstName, 
        LastName,
        IsNull((
            SELECT  COUNT(UP1.EmailAddress) AS HasEmail 
            From    dbo.UserProfiles AS UP1 
            WHERE   (NOT (UP1.EmailAddress IS NULL)) 
                    AND (CreatedBy = dbo.UserProfiles.UserID)
            GROUP BY CreatedBy), 0) AS EmailEnteredCount 
FROM    dbo.UserProfiles 
WHERE   (IsStaff = 1)

答案 1 :(得分:1)

如果你的isnull在你的计数范围之内会更有意义。试试这个:

count(isnull(up1.emailaddress, 0))