mysql sum(if())和count(if())用法

SELECT SUM(extcredits1) AS e1 FROM test;
SELECT SUM(if(category=1,size,0)) ,COUNT(if(category=1,true,null)) FORM t_file; 

解析: 

sum(if(category=1,size,0))

 sum函数返回一个值类型的数值,如果category=1,则返回size,如果category不等于1就返回0。 

 count(if(category=1,true,null))

count函数返回一个布尔值类型的数值,如果category=1,返回true,如果category不等于1返回null,如果写成count(If(category=1,1,0) 则返回的全是true,也就是说全都会计数,而count()间断内容是true还是null,如果不是null就计数,

如果是null就不计数。

count(if())的写法应该是count(if(表达式表达式,true,null));

 示例:

原表:

id    fenlei     time
1      分类1      20130316
2      分类2      20130316
3      分类3      20130317
4      分类2      20130317
5      分类3      20130318

需要查上表,得到结果插入新表
新表结构:

id     fenlei_1   fenlei_2   fenlei_3   date
1      1             1          0         20130316
2      0             1          1         20130317
3      0             0          1         20130317

即要得到每个分类在每天各自消息数

select time,sum(if(fenlei='分类1',1,0 )),
sum(if(fenlei='分类2',1,0 )),sum(if(fenlei='分类3',1,0 ))
from tt
group by time

来一个简单的sum

select sum(qty) as total_qty from inventory_product group by product_id

这样就会统计出所有product的qty.

但是很不幸,我们的系统里面居然有qty为负值。而我只想统计那些正值的qty,加上if function就可以了。 SQL为:

select sum(if(qty > 0, qty, 0)) as total_qty   from inventory_product group by product_id

意思是如果qty > 0, 将qty的值累加到total_qty, 否则将0累加到total_qty.

再加强一点:

select
sum( if( qty > 0, qty, 0)) as total_qty   ,
sum( if( qty < 0, 1, 0 )) as negative_qty_count
from inventory_product 
group by product_id

这样就可以统计有多少条负值的记录了。方便程序用来告诉人们这条记录数据异常
 

正因为当初对未来做了太多的憧憬,所以对现在的自己尤其失望。生命中曾经有过的所有灿烂,终究都需要用寂寞来偿还。
原文地址:https://www.cnblogs.com/candlia/p/11919949.html