SQL Server查询使用Count和GroupBy显示null而不是0

时间:2013-05-20 17:25:31

标签: sql-server sql-server-2008 tsql

我有以下查询:

select 
     Pr.Name, PS.TotalSales, PS.Truesales
From 
     Product Pr
Left Join 
     (select ProdudtId, TotalSales = COUNT(Transaction.Id),
            Truesales = COUNT(DISTINCT case when .Transaction.ExceptionCode  = ' ' then Transaction.Id END)
     from [Transaction] 
     WHERE   
        (ResponseTime < '2013/05/16 01:53:52' and  RequestTime > '2013/05/11 01:53:52')
     Group By 
          ProductId) PS on PS.ProductId = Pr.ProductId

我得到这样的结果:

Name TotalSales  TrueSales
AB     3             2
CD     NULL          NULL
EF     1              1

我想得到像这样的结果

Name TotalSales  TrueSales
AB     3             2
CD     0             0
EF     1              1

我希望看到0代替空值。 谁能告诉我在查询中需要做出哪些改变?

这两个表格如下:

    1 ) Product 
    ProuctId, Name 

2) Sales
TransactionId, ReqTime, ResTime, ProductId(FK), ExceptionCode

2 个答案:

答案 0 :(得分:2)

select Pr.Name, isnull(PS.TotalSales, 0) TotalSales, isnull(PS.Truesales, 0) Truesales
From Product Pr
Left Join (
select ProdudtId, TotalSales = COUNT(Transaction.Id),
Truesales = COUNT(DISTINCT case when .Transaction.ExceptionCode  = ' ' then Transaction.Id END)
from [Transaction] 
WHERE   
(ResponseTime < '2013/05/16 01:53:52' and  RequestTime > '2013/05/11 01:53:52')
Group By ProductId) PS on PS.ProviderId = Pr.ProviderId

答案 1 :(得分:2)

更改此行

select Pr.Name, PS.TotalSales, PS.Truesales

select Pr.Name, IsNull(PS.TotalSales, 0) AS TotalSales, IsNull(PS.Truesales, 0) AS Truesales