gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:47:20 25 4
gpt4 key购买 nike

我有以下代码:

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)

示例结果:

姓氏电子邮件输入计数

账单为空

拉尔森 51

科视 30

教区空

senac 为空

代码正确执行,但有一个异常(exception),当没有找到记录时它返回空值而不是预期的 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

如有任何帮助,我们将不胜感激。

谢谢,克里斯

最佳答案

您需要将 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)

关于tsql - ISNULL(Count(x),0) null 时不返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21291136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com