日期:2014-05-16  浏览次数:20507 次

DB2中使用sum替代count的查询

sum函数是对列的值进行统计,求和;

count函数对满足条件的列进行累计,满足条件就加一。

常用count函数来统计满足某条件的记录数,如,统计学生信息表student中的男生人数:

select count(*) from student where sex='M'

常用sum函数来对满足条件的数据进行求和,如,计算学生成绩表score中'Scott'的总成绩:

select sum(achv) from score where stu_name='Scott' and stu_id='120010'

其实除了统计所有表中的行外,其他情况下的count都能用sum来替代。

例如上面统计学生中男生人数,可以这样写:

select sum(case when sex='M' then 1 else 0 end)
  from student

例2:统计employee中所有员工数量,和男性员工数量

select 'all',count(*) 
  from employee 
 union all 
select 'man',count(*) 
  from employee 
 where sex='M'
1   2
--- -----------
man          23
all          42

下面是使用sum函数来替代count男性员工:

select 'man',sum(case when sex='M' then 1 else 0 end) 
  from employee
 union all 
select 'all',count(*) 
  from employee
1   2
--- -----------
all          42
man          23
如果要统计所有男性人数和所有女性人数,还有所有员工人数呢?

如果使用count函数,则需要写三个查询,然后将其union all起来,得到我们的数据:

select 'man',count(*) 
  from employee 
 where sex='M' 
 union all 
select 'femail',count(*) 
  from employee 
 where sex ='F' 
 union all 
select 'all',count(*) 
  from employee 
1      2
------ -----------
man             23
femail          19
all             42

这个查询的实现,需要读取三次表,效率自然而然低,那我们为何不在一次读取表的时候,都统计到呢?

读一次表统计所有数据,那么count(*),count(column_name),count(0),count(null)等这些统计的结果相同吗?

count(*)常用于统计符合条件的行数;

count(0)或者count(1)在统计符合记录的行数目,与count(*)相同作用;

count(column_name)就不一样了,它将会过滤掉column is null的值。

select count(case when 1=0 then 1 else null end)cnt1,
       count(case when 1=1 then 1 else null end) cnt2
 from sysibm.sysdummy1
CNT1        CNT2
----------- -----------
          0           1
再来看下面一个例子:

db2 => select * from test01
COL1  COL2
----- -----
A01   -
-     B01
-     -
A02   B02
A03   -

db2 => select count(*) cnt1,count(1) cnt2,count(col1) cnt3,count(col2) cnt4 from test01
CNT1        CNT2        CNT3        CNT4
----------- ----------- ----------- -----------
          5           5           3           2

count是对符合条件的记录进行统计,也就是说我们读取一条记录,判断其符合条件之后,就让统计变量自增1,

这样碰到下一条符合记录的数据时又自增1,直到读取到表中数据的末尾;

我们可以使用sum来对count进行替代,也就是说在找到符合记录的时候就加1,没符合条件的记录就加0;

这样就可以使用sum替代count来统计employee表中数据,而且只需要读取一次表:

select count(*) all,
       sum(case when sex='M' then 1 else 0 end) man,
       sum(case when sex='F' then 1 else 0 end) femail
  from employee
ALL         MAN         FEMAIL
----------- ----------- -----------
         42          23          19
这个查询在实际当中使用得最多,根据同样的输入,统计一个或多个字段中不同标志的记录数。

--the end--