SQL Server - 使用ISNULL消除NULL读取

时间:2016-07-02 23:02:21

标签: sql sql-server sql-server-2008 isnull

我已完成查询,运行正常。现在我正在修改它,以便输出显示[$0]而不是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       $852.94          $12371.41       $1015.16 
     02       $4192.21          $3714.74       NULL
     03       $215.73           NULL           NULL 

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

我会这样做。让每个内联视图返回纯数值。在外部查询中,包装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