create table t(id int, col int)
insert t select 1, 100--1, 正常
select * from t where id=2
/*
(0 row(s) affected)
*/--2, 正常
select id,isnull(sum(col),0) as total from t where id=2 group by id  
/*
(0 row(s) affected)
*/--3***问题在这句:为什么会有一条记录?
select isnull(sum(col),0) as total from t where id=2  
/*
total       
----------- 
0(1 row(s) affected)
*/drop table t

解决方案 »

  1.   

    select sum(col) from t where id=2  
    查出来为Null
    isnull 判断了就为0啊
      

  2.   

    select id,isnull(sum(col),0) as total from t where id=2 group by id  这个查询的结果中,要求有id,表中没有id=2的记录
    没有结果是正常的select isnull(sum(col),0) as total from t where id=2  这个查询的结果,只是求col的和,没有就0,无论如何都会有一个记录的
      

  3.   

    还真的是呀,第二个的时候是查了2个列,就没有,第三个单查一个列并判断null值就有呀
      

  4.   

    select  isnull(sum(col),0)  as total from t where id=2
    这样理解
    select  sum(col)  as total from t where id=2 这样得到的结果是null
    再加上isnull(cum(col),0)就是0了
      

  5.   

    select id,isnull(sum(col),0) as total from t where id=2 group by id 
    从t表中查询id=2的元组,从这个元组中显示两个列id和total,再分组显示
    因为id=2没有这个元组,所以结果集为空
    select isnull(sum(col),0) as total from t where id=2 
    从t表中查询id=2的元组,查询total列,如果值为控制则用0代替
    所以有结果集
      

  6.   

    select id,isnull(sum(col),0) as total from t where id=2 group by id 
    可以这样看
    select isnull(sum(col),0) as total from t where id=2 group by id 
    这样得到的结果是没有,因为是根据id分组,没有id=2的组,所以没有记录
    再加上id列一样
      

  7.   

    其实呢两个差别是,第一个查两个列,一个列为原列,另一个为判断列,如果id列也做isnull判断肯定就有值了
      

  8.   

    空记录集和空值是不一样的。SELECT NULL               --空值,1条记录。
    SELECT NULL WHERE 1 <> 1  --空记录集,0条记录。
    SELECT SUM(col) FROM [table]
    含义是计算表中所有col的和。若无记录或col都为NULL,则结果为NULL。
    该查询一定会返回且只返回一条记录,不管表中有没有数据。这个SUM换成别的聚合函数也一样。SELECT id,SUM(col) FROM [table] GROUP BY id
    含义是为表中每一个id计算col的和。若无记录,即不存在任何id,结果则是空记录集。
      

  9.   

    --1)观察如下查询和结果select COUNT(col) as total from t where id=2total
    -----------
    0(1 row(s) affected)select MAX(col) as total from t where id=2  total
    -----------
    NULL(1 row(s) affected)--2)相关解释自然聚合函数MIN AVG SUM等的返回结果仍旧是NULL.
    这是聚合函数的处理方式,如果结果集影响的行数为0,在聚合函数里当NULL处理
      

  10.   

    我看了一下,大家都没看懂lz的问题,直接就回答了。做如下测试,就很清楚了
    create table t(id int, col int)
    insert t select 1, 100select isnull(sum(col),0) as total from t where id=2 
    /*
    total       
    ----------- 
    0(所影响的行数为 1 行)
    */
    select isnull(sum(col),0) as total from t where id=2  group by id
    /*total       
    ----------- (所影响的行数为 0 行)
    */