使用SQL语句统计数据时sum和count函数中使用if判断条件

首先举个栗子(不想看的话直接下面看总结):

SELECT

date(create_time) AS '当天日期',

sum(real_price) AS '当天总收入',

sum函数中使用if判断条件:{

sum(
IF (order_type = 0, real_price, 0)
) AS '当天支付收入',
sum(
IF (order_type = 1, real_price, 0)

) AS '当天打赏收入',

}

        count(DISTINCT open_id) AS '付费总人数',

count函数中使用if判断条件:{

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函数中使用if判断条件:{

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)

查询结果:order_type为订单类型,为了区分打赏订单和支付订单的数据统计,使数据更加清晰。


总结:

sum函数中使用if判断条件格式为:

1.单条件判断格式,sum(if(条件字段名=值,需要计算sum的字段名,0))

2.多条件判断格式,sum(IF(条件字段名>值 AND 条件字段名>值 AND 条件字段名=值,1,0))

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))

猜你喜欢

转载自blog.csdn.net/qq784515681/article/details/80375494