sum(if())使用
原表:
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
这样就可以统计有多少条负值的记录了。方便程序用来告诉人们这条记录数据异常
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号