最后有一个distinct使用的坑要注意——有多个字段时子过滤一个字段的问题。
先从一个案例开始吧,有一张充值日志表,我需要按天统计出充值总人数,已付款成功人数,未付款成功人数。
表构建如下:
create table log_recharge(
oid int(11) not null auto_increment primary key,
ouser_id int(11) not null default 0,
oamount DECIMAL(20) not null default 0,
ocreated timestamp not null default current_timestamp,
ostatus enum('paid','unpaid') not null default 'paid'
);
在没看下面查询语句前试想该怎么写这条sql。
重点来了,sql如下。
SELECT date(created) as date,
ocount(distinct user_id) as recharge_num,
ocount(distinct case when status = 'paid' then user_id else null end) as paid_num,
ocount(distinct case when status = 'unpaid' then user_id else null end) as unpaid_num
FROM `log_recharge` where 1=1 group by 1;
//date://时间
//recharge_num:充值人数;
//paid_num:已充值成功人数;
//unpaid_num:未充值成功人数;
和你想的sql有什么不同,有的话就在下方留言,一起探讨一下吧。
以上的查询还是比较清晰的,在实际项目中可能要比这复杂的多。对于特定的查询我们可以有针对的抽丝剥茧出来单独测试,以上的案例就是从复杂查询剥离出来的一次测试。
最后有一个distinct使用的坑要注意——有多个字段时子过滤一个字段的问题。
//这种方式过滤的是user_id和game_id
select distinct user_id,game_id from log_game;
//正确的姿态可以这么处理
select user_id,game_id,count(distinct user_id) from log_game
有多字段但只过滤单个字段请使用count(distinct field)过滤方式。
除特别注明外,本站所有文章均为作者原创。 或分享自己的编程经验,或探讨工作中的问题,或聊以人生趣事。 转载请注明出处来自 https://www.qiusuoweb.com/89.html
运营天数
总访问量
文章数量
-
-
-
交流群:157451741
新浪微博:草莽兴
发布评论