题解 | 商品销售总额分布(case when与if())
商品销售总额分布
https://www.nowcoder.com/practice/62909494cecd4eab8c2501167e825566
# 需要小明展示商品名称为'anta'的商品各个支付渠道的分布(包括脏数据数量),以支付渠道的次数的逆序排列返回 # 注: # 只有select步骤的数据有pay_method字段; # 如果select中pay_method为''则以error标记pay_method为脏数据; select pay_method,count(*) cnt from( select product_id ,case when pay_method = '' then 'error' else pay_method end as pay_method from user_client_log where step='select' ) t left join product_info t1 on t.product_id=t1.product_id where product_name='anta' group by t.pay_method order by cnt desc; # select # case when pay_method = '' then 'error' else pay_method end as pay_method # ,count(*) cnt # from user_client_log t # join product_info t1 # on t.product_id=t1.product_id # where step='select' and product_name='anta' # group by t.pay_method # order by cnt desc; # if()是非标准SQL,会被优化器做如下优化 # 优化器可能将 IF() 的计算推迟到 JOIN 之后(尤其是 pay_method 来自 JOIN 的表时)。导致 GROUP BY t.pay_method 引用的是原始 pay_method(可能仍是 NULL),而非子查询中的 'error'。 # 反正以后优先用case when
优先用case when
if()只有MySQL支持