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
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
查出来为Null
isnull 判断了就为0啊
没有结果是正常的select isnull(sum(col),0) as total from t where id=2 这个查询的结果,只是求col的和,没有就0,无论如何都会有一个记录的
这样理解
select sum(col) as total from t where id=2 这样得到的结果是null
再加上isnull(cum(col),0)就是0了
从t表中查询id=2的元组,从这个元组中显示两个列id和total,再分组显示
因为id=2没有这个元组,所以结果集为空
select isnull(sum(col),0) as total from t where id=2
从t表中查询id=2的元组,查询total列,如果值为控制则用0代替
所以有结果集
可以这样看
select isnull(sum(col),0) as total from t where id=2 group by id
这样得到的结果是没有,因为是根据id分组,没有id=2的组,所以没有记录
再加上id列一样
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,结果则是空记录集。
-----------
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处理
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 行)
*/