如果在sql语句中结果为NULL,如何将结果更改为0

时间:2010-12-31 06:26:35

标签: sql-server

我有一个select语句,比如......

select col1, col2, col3 from tbl1 where (conditions)

如果没有行,

我所看到的只是......

NULL,NULL,NULL

我想要的是

0,0,0

我知道有......好像..

select when (condition) then RESULT else 0 end as 'Col1',..... from tbl1

但是,如果我这样做,我必须检查条件每行..

更好的主意??

2 个答案:

答案 0 :(得分:2)

试试这个:

select isnull(col1,0) from tbl1

另一种方法,如果你打算获得1行但没有得到任何一种,你可以使用sum coalesce方法:

select coalesce(sum(col1),0) from tbl1

另一个,使用WITH,因此当过滤不产生任何结果时,您不必重新评估行:

with result as
(
    select col1, col2, col3 from tbl1 
    where 1 = 0 -- your condition goes here
)
select col1, col2, col3 from result
union
select 0, 0, 0 where not exists(select * from result)

答案 1 :(得分:0)

对于这种类型的查询,你可以使用sql的nvl函数。下面给出的语法..

Nvl( null value colum,0)               

示例 - 如果一个人没有得到comisition那么查询将是...

Select  nvl( cmsn_pct,0) from employee;
相关问题