如何将空记录转换为零

时间:2014-12-11 22:17:01

标签: sql isnull

我正在开发销售点系统,但最近我被搁浅了。我有两个表,我想从中选择数据,但我检索的一些值是NULL s,而我需要它们为零。如果一个表([dbo.ProdDetails])中有一行而另一个表[dbo.Pro_Sales]中没有相应的行,则会发生这种情况。

我正在使用此查询:

 SELECT a.ItemCODE,a.OpenStock,c.UnitsSold
 FROM
   (SELECT  x.ItemCODE,x.OpenStock FROM  dbo.ProdDetails x) a
   LEFT OUTER JOIN

   (SELECT  x.ProductID,ISNULL(CONVERT(varchar(50),x.Quantity),'') UnitsSold
    FROM  dbo.Pro_Sales  x
    GROUP BY x.ProductID,x.Quantity
    ) c
 ON a.ItemCODE=c.ProductID

 WHERE a.ItemCODE ='0005'

结果是

itemCode OpenStock UnitsSold 0005 6 NULL

2 个答案:

答案 0 :(得分:0)

使用ISNULL(columnName,alt.Value)作为columnName:

SELECT a.ItemCODE,a.OpenStock,ISNULL(c.UnitsSold,0) as UnitsSold
 FROM
   (SELECT  x.ItemCODE,x.OpenStock FROM  dbo.ProdDetails x) a
   LEFT OUTER JOIN

   (SELECT  x.ProductID,ISNULL(CONVERT(varchar(50),x.Quantity),'') UnitsSold
    FROM  dbo.Pro_Sales  x
    GROUP BY x.ProductID,x.Quantity
    ) c
 ON a.ItemCODE=c.ProductID

 WHERE a.ItemCODE ='0005'

答案 1 :(得分:0)

这是COALESCE()函数的用途:

SELECT a.ItemCODE, a.OpenStock, COALESCE(c.UnitsSold, 0) AS UnitsSold
FROM
  (SELECT  x.ItemCODE,x.OpenStock FROM  dbo.ProdDetails x) a
  LEFT OUTER JOIN
   (SELECT  x.ProductID,ISNULL(CONVERT(varchar(50),x.Quantity),'') UnitsSold
   FROM  dbo.Pro_Sales  x
   GROUP BY x.ProductID,x.Quantity
   ) c
ON a.ItemCODE=c.ProductID
WHERE a.ItemCODE ='0005'