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中所有员工数量,和男性员工数量

  1. select'all',count(*)
  2. from employee
  3. unionall
  4. select'man',count(*)
  5. from employee
  6. where sex='M'
  7. 1 2
  8. --- -----------
  9. man 23
  10. all 42

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

  1. select'man',sum(casewhen sex='M'then 1 else 0 end)
  2. from employee
  3. unionall
  4. select'all',count(*)
  5. from employee
  6. 1 2
  7. --- -----------
  8. all 42
  9. man 23

如果要统计所有男性人数和所有女性人数,还有所有员工人数呢?

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

  1. select'man',count(*)
  2. from employee
  3. where sex='M'
  4. unionall
  5. select'femail',count(*)
  6. from employee
  7. where sex ='F'
  8. unionall
  9. select'all',count(*)
  10. from employee
  11. 1 2
  12. ------ -----------
  13. man 23
  14. femail 19
  15. all 42

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

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

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

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

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

  1. selectcount(casewhen 1=0 then 1 elsenullend)cnt1,
  2. count(casewhen 1=1 then 1 elsenullend) cnt2
  3. from sysibm.sysdummy1
  4. CNT1 CNT2
  5. ----------- -----------
  6. 0 1

再来看下面一个例子:

  1. db2 => select * from test01
  2. COL1 COL2
  3. ----- -----
  4. A01 -
  5. - B01
  6. - -
  7. A02 B02
  8. A03 -
  9. db2 => selectcount(*) cnt1,count(1) cnt2,count(col1) cnt3,count(col2) cnt4 from test01
  10. CNT1 CNT2 CNT3 CNT4
  11. ----------- ----------- ----------- -----------
  12. 5 5 3 2

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

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

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

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

  1. selectcount(*) all,
  2. sum(casewhen sex='M'then 1 else 0 end) man,
  3. sum(casewhen sex='F'then 1 else 0 end) femail
  4. from employee
  5. ALL MAN FEMAIL
  6. ----------- ----------- -----------
  7. 42 23 19

这个查询在实际当中使用得最多,根据同样的输入,统计一个或多个字段中不同标志的记录数。

--the end--

  • 1
  • 2
  • 下一页

相关内容