题解 | 商品销售总额分布(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支持

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 11:31
点赞 评论 收藏
分享
下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:23
转人工😡
门口唉提是地铁杀:五次握手了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务