TSQL 聚合函数忽略NULL值

来源:互联网 发布:慈溪行知职高分数线 编辑:程序博客网 时间:2024/05/16 08:00

max,min,sum,avg聚合函数会忽略null值,但不代表聚合函数不返回null值,如果表为空表,或聚合列都是null,则返回null。count 聚合函数忽略null值,如果聚合列都是null或表为空表,则返回0。

共性:Null values are ignored.

一,聚合函数忽略NULL值

示例数据表

create table dbo.ftip( ID int)

1,当表中没有任何数据时,聚合函数的返回值

select max(ft.ID),min(ft.ID),sum(ft.ID),AVG(ft.ID),count(ft.ID)from dbo.ftip ft with(NOLOCK)

2,当表中存在数据时,聚合函数对null值得处理

2.1, 表中数据只有null

insert into dbo.ftipvalues(null)
select max(ft.ID),min(ft.ID),sum(ft.ID),AVG(ft.ID),count(ft.ID)from dbo.ftip ft with(NOLOCK)

 2.2 表中的数据含有null,也含有非null

insert into dbo.ftipvalues(1)select max(ft.ID),min(ft.ID),sum(ft.ID),AVG(ft.ID),count(ft.ID)from dbo.ftip ft with(NOLOCK)

3,count(*)或count(0)的特殊之处,不检查null值,返回分组的总行数

select count(ft.ID),count(0),count(*)from dbo.ftip ft with(NOLOCK)

4,在group by子句中,SQL Server 认为所有的null值是相同的,所有的null值分到同一个组中。

select ft.ID,count(ft.ID),count(0),count(*),max(ft.ID),min(ft.ID),sum(ft.ID),AVG(ft.ID)from dbo.ftip ft with(NOLOCK)group by ft.ID

5,聚合函数会忽略Null值,对非NULL的值进行聚合。

insert into dbo.ftipvalues(2)select max(ft.ID),min(ft.ID),sum(ft.ID),AVG(ft.ID),count(ft.ID)from dbo.ftip ft with(NOLOCK)

二,聚合函数Count的不同写法

Count有三种写法:count(*),count(expression),count(column_name),计数说明:

  • Count(expression) ,count(column_name)计数的机制是:计算 expression,或表中column_name的值是否为NULL,如果为NULL则不计数,如果不是NULL则会计数;
  • count(*),返回表中行的数目。Specifies that all rows should be counted to return the total number of rows in a table,即使有null或duplicate value,也会计算在内;
  • 如果Expression或column_name的值不是null,count(expression),count(column_name)和count(*)返回的结果是相同的;

1,创建示例数据

create table dbo.test(id int)insert into dbo.testvalues(1),(2),(null)

2,测试 count(expression)

DECLARE @var int=nullselect count(@var) from dbo.test

结果分析:返回的结果是0,原因是expression是null,count函数对null值不计数。

3,测试count(0),count(*)

select count(*), count(0) from dbo.test

结果分析:返回的结果都是3,说明count(*)计算表的行数,不排除null值或duplicate值。由于0是非null值,count(0)和count(*)执行结果是相同的。

4,测试count(column_name)

select count(id) from dbo.test

结果分析:返回的结果是2,从表中取出id值,如果为null,则不计数;如果不是null,则计数。

0 0