如果在T-SQL中记录为NULL,如何替换字符串

我正在撰写一份T-sql报告,显示不同客户处于不同状态的帐户数量.报告结果如下:
Customer1    NoService        7
Customer1    IncompleteOrder  13
Customer1    NULL             9
Customer2    NoService        12
Customer2    Available        19
Customer2    NULL             3
...

‘NULL’状态是有效数据,但我想显示“Pending”而不是显示NULL.到目前为止,这是我的sql

USE cdwCSP;
SELECT
   sr.sales_region_name   AS SalesRegion,micv.value,COUNT(sr.sales_region_name)
FROM prospect p
   LEFT JOIN sales_region sr
     ON p.salesRegionId = sr.sales_region_number
   LEFT JOIN prospectOrder po
     ON po.prospectId = p.prospectId
   LEFT JOIN wo
     ON wo.prospectId = p.prospectId
   LEFT JOIN woTray wot
     ON wot.woId = wo.woId
   LEFT JOIN miscinformationCustomerCategory micc
     ON micc.prospectId = p.prospectId
   LEFT JOIN miscinformationCustomerValues micv
     ON micv.miscinformationCustomerCategoryId = micc.miscinformationCustomerCategoryId
   LEFT JOIN miscinformationCategory mic
     ON micc.miscinformationCategoryId = mic.miscinformationCategoryId
WHERE wot.dateOut IS NULL
     AND mic.categoryName LIKE '%serviceability%'
GROUP BY sr.sales_region_name,micv.value
ORDER BY sr.sales_region_name,micv.value;

任何帮助将不胜感激,我仍然在学习T-sql,所以这可能是一个容易回答的问题.

解决方法

您可以使用 COALESCE或ISNULL.前者是标准的并返回第一个NOT NULL参数(如果所有参数都为NULL,则返回NULL)
SELECT COALESCE(micv.value,'Pending') as value

ISNULL仅限于2个参数,但如果要测试的第一个值很昂贵(例如子查询),则sql Server中的效率更高.

ISNULL要注意的一个潜在“问题”是它返回第一个参数的数据类型,因此如果要替换的字符串比列数据类型允许的话,则需要进行强制转换.

例如.

CREATE TABLE T(C VARCHAR(3) NULL);

INSERT T VALUES (NULL);

SELECT ISNULL(C,'UnkNown')
FROM T

将返回Unk

但ISNULL(CAST(C as VARCHAR(7)),’UnkNown’)或COALESCE都可以按预期工作.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...