SQL 服务器 - 使用 ISNULL 消除 NULL 读取

SQL Server - Using ISNULL to eliminate NULL reading

我已经完成了一个查询,它运行良好。现在我正在努力修改它,以便输出显示 [[=13=]] 而不是 NULL.
有谁知道具体怎么做?

这是我所做的:

Select  I.Store
      , I.ISNULL([Inventory $ TOTAL],0)
      , S.ISNULL([Sales $     TOTAL],0)
      , R.ISNULL([Receipts $ TOTAL],0) 
From 
     ( Select   Store
             , '$'+Cast(Sum(QTY*Cost) As Varchar(20)) [Inventory $   TOTAL]
      From Inventory Group By Store
      ) I
Left Outer Join
     ( Select Store
           , '$'+Cast(Sum(QTY*Unit_Price) As Varchar(20)) [Sales $  TOTAL]
      From Sales Group By Store
     ) S 
         On S.Store = I.Store 
Left Outer Join
    ( Select  Store
            , '$'+Cast(Sum(QTY*Unit_Cost) As Varchar(20)) [Receipts $  TOTAL]
      From Receipts Group By Store
    ) R 
         On R.Store = I.Store 

-- 这是输出

    Store   Inventory TOTAL   SALES TOTAL   RECEIPTS TOTAL
     01       2.94          371.41       15.16 
     02       92.21          14.74       NULL
     03       5.73           NULL           NULL 
Select  I.Store
      , '$'+ ISNULL(Cast(Sum(I.QTY * I.Cost)       As Varchar(20)) , '0') AS [Inventory $   TOTAL]
      , '$'+ ISNULL(Cast(Sum(S.QTY * S.Unit_Price) As Varchar(20)) , '0') AS [Sales $  TOTAL]
      , '$'+ ISNULL(Cast(Sum(R.QTY * R.Unit_Cost)  As Varchar(20)) , '0') AS [Receipts $  TOTAL]
From Inventory I
Left Outer Join Sales    S On S.Store = I.Store 
Left Outer Join Receipts R On R.Store = I.Store 
GROUP BY I.Store

我怀疑您遇到的问题是打字问题。子查询明确地将每个值转换为一个字符,因此您应该使用一个字符作为 NULL 默认值:

Select I.Store,
       COALESCE(I.[Inventory $ TOTAL], '[=10=]'),
       COALESCE(S.[Sales $     TOTAL], '[=10=]'),
       COALESCE(R.[Receipts $ TOTAL], '[=10=]') 

我更喜欢 COALESCE() 而不是 ISNULL(),因为 COALESCE() 是 ANSI 标准。

我会这样做。让每个内联视图 return 具有纯数值。在外部查询中,将来自每个内联视图的数值包装在 SQL Server ISNULL 函数(或 ANSI COALESCE 函数)中,然后围绕它进行格式化。处理最外层查询中的所有转换和格式设置。

  SELECT i.store
       , '$'+CAST( ISNULL(i.si_total,0) AS VARCHAR(20)) AS  [Inventory $   TOTAL]
       , '$'+CAST( ISNULL(s.ss_total,0) AS VARCHAR(20)) AS  [Sales $  TOTAL]
       , '$'+CAST( ISNULL(r.sr_total,0) AS VARCHAR(20)) AS  [Receipts $  TOTAL]
    FROM ( SELECT si.Store
                , SUM(si.QTY*si.Cost)         AS si_total
             FROM Inventory si
            GROUP BY si.Store
         ) i
    LEFT
    JOIN ( SELECT ss.Store
                , SUM(ss.QTY*ss.Unit_Price)   AS ss_total
             FROM Sales ss
            GROUP BY ss.Store
         ) s
      ON s.Store = i.Store
    LEFT
    JOIN ( SELECT sr.Store
                , SUM(sr.QTY*sr.Unit_Cost)    AS sr_total
             FROM Receipts sr
            GROUP BY sr.Store
         ) r
      ON r.Store = i.Store
   ORDER BY i.Store