Chr*_*ris 2 t-sql 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)
Run Code Online (Sandbox Code Playgroud)
样本结果:
姓氏EmailEnteredCount
帐单为空
拉尔森51
佳士得30
零值
senac NULL
该代码可以正确执行,但有一个例外,当未找到任何记录而不是预期的0时,它将返回一个空值。
更新:这将返回我要完成的工作,只是需要一个更清洁的解决方案。我真的不认为我需要创建一个临时表来替换一个空值。
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
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激。
谢谢克里斯
您需要将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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12518 次 |
| 最近记录: |