如何用空字符串替换空字段值?

时间:2019-08-05 16:52:21

标签: sql sql-server ssms

我需要用空白字符串替换“估计数”字段中的空值。我已经尝试了下面的代码,但值仍然显示为null。有什么想法吗?谢谢

Pro Number      Estimate Number

10271943        NULL
10271944        NULL
10271945        NULL
10271946        NULL
10271948        94606


SELECT a.AAAREFNUMVALUE AS "Pro Number",
    (SELECT TOP 1 isnull(a2.AAAREFNUMVALUE,'') 
    FROM dbo.AAATOREFNUMS a2
    WHERE a2.AAATRANSPORTTABLE  = a.AAATRANSPORTTABLE  AND 
    a2.AAAREFNUMTYPE = 4 
    ORDER BY a2.AAAREFNUMVALUE
    ) AS "Estimate Number"

FROM dbo.AAATOREFNUMS a 
INNER JOIN dbo.AAATODATES d ON a.AAATRANSPORTTABLE = d.AAATRANSPORTTABLE

WHERE a.AAAREFNUMTYPE = 1 AND d.AAADATETYPE = 1  
GROUP BY a.AAAREFNUMVALUE,a.AAATRANSPORTTABLE,a.AAAREFNUMTYPE;

3 个答案:

答案 0 :(得分:2)

当子查询不返回任何值时,会出现问题。 isnull()需要移到子查询之外

ISNULL( (SELECT TOP 1 a2.AAAREFNUMVALUE
         FROM dbo.AAATOREFNUMS a2
         WHERE a2.AAATRANSPORTTABLE  = a.AAATRANSPORTTABLE  AND 
               a2.AAAREFNUMTYPE = 4 
         ORDER BY a2.AAAREFNUMVALUE
        ), ''
      ) AS "Estimate Number"

请注意,在这种情况下,ISNULL()COALESCE()更为可取,因为COALESCE()的SQL Server实现在第一个参数不是NULL时对第一个参数进行两次求值。

但是,如果改为使用窗口函数,您可能会发现查询更易于表达并且运行速度更快:

SELECT DISTINCT a.AAAREFNUMVALUE AS "Pro Number",
       COALESCE(a.AAAREFNUMVALUE_4, '') as "Estimate Number"
FROM (SELECT a.*,
             MAX(CASE WHEN a.AAAREFNUMTYPE = 4 THEN a.AAAREFNUMVALUE END) OVER (PARTITION BY a.AAATRANSPORTTABLE) as AAAREFNUMVALUE_4
      FROM dbo.AAATOREFNUMS a
     ) a INNER JOIN
     dbo.AAATODATES d
     ON a.AAATRANSPORTTABLE = d.AAATRANSPORTTABLE
WHERE a.AAAREFNUMTYPE = 1 AND d.AAADATETYPE = 1  ;

答案 1 :(得分:1)

尝试案例,只需进行调整即可:

CASE 
(SELECT TOP 1 a2.AAAREFNUMVALUE
    FROM dbo.AAATOREFNUMS a2
    WHERE a2.AAATRANSPORTTABLE  = a.AAATRANSPORTTABLE  AND 
    a2.AAAREFNUMTYPE = 4 
    ORDER BY a2.AAAREFNUMVALUE) as Estimate Number
  WHEN NULL THEN ''
  ELSE 
    a2.AAAREFNUMVALUE
END as "Estimate Number"

答案 2 :(得分:0)

您可以尝试这个。

SELECT a.AAAREFNUMVALUE AS "Pro Number",
    ISNULL((SELECT TOP 1 isnull(a2.AAAREFNUMVALUE,'') 
    FROM dbo.AAATOREFNUMS a2
    WHERE a2.AAATRANSPORTTABLE  = a.AAATRANSPORTTABLE  AND 
    a2.AAAREFNUMTYPE = 4 
    ORDER BY a2.AAAREFNUMVALUE
    ),'') AS "Estimate Number"

FROM dbo.AAATOREFNUMS a 
INNER JOIN dbo.AAATODATES d ON a.AAATRANSPORTTABLE = d.AAATRANSPORTTABLE

WHERE a.AAAREFNUMTYPE = 1 AND d.AAADATETYPE = 1  
GROUP BY a.AAAREFNUMVALUE,a.AAATRANSPORTTABLE,a.AAAREFNUMTYPE;