首先举个栗子(不想看的话直接下面看总结):
order_type:订单类型 open_id:用户唯一标识 SELECT date(create_time) AS ‘当天日期‘, sum(real_price) AS ‘当天总收入‘, sum(IF (order_type = 0, real_price, 0)) AS ‘当天支付收入‘, sum(IF (order_type = 1, real_price, 0)) AS ‘当天打赏收入‘, count(DISTINCT open_id) AS ‘付费总人数‘, count(DISTINCT open_id,IF (order_type = 0, TRUE, NULL)) AS ‘支付人数‘, count(DISTINCT open_id,IF (order_type = 1, TRUE, NULL)) AS ‘打赏人数‘, count(id) AS ‘付费订单总数‘, count(DISTINCT id,IF (order_type = 0, TRUE, NULL)) AS ‘支付订单数‘, count(DISTINCT id,IF (order_type = 1, TRUE, NULL)) AS ‘打赏订单数‘ FROM orders WHERE ‘real_price‘ != 1 AND ‘status‘ != 0 GROUP BY DATE(create_time)
查询结果:为了区分打赏订单和支付订单的数据统计,使数据更加清晰
小结:
sum函数中使用if判断条件格式为:sum(if(条件,列值,0))
注解:sum是求和函数,条件为真时,执行列值(字段名)求和也就是累加,条件为假时为0求和(当然还是0)
1.单条件判断格式,sum(if(条件字段名=值,需要计算sum的字段名,0))
2.多条件判断格式,sum(if(条件字段名>值 AND 条件字段名>值 AND 条件字段名=值,1,0))
注解:多条件判断格式整体含义为,计算满足条件的数据总数,如果满足条件,那么数据总数加1,所以1的含义为累加1
3.常见case when格式,sum(case when 条件字段名 in (范围较小值,范围较大值) then [需要计算sum的字段名] else 0 end)
count函数中使用if判断条件格式为:
1.统计总数,count(if(条件字段名=值,true,null))
2.统计总数去重复值,count(DISTINCT 需要计算count的字段名,if(条件字段名=值,true,null))