假如有一张表 table,user_id,login_ip,create_time 记录用户每天登陆数据,
我想分组统计 一周登陆5次以下用户占比,5次~10次用户占比,10~20次占比如果我按照月统计,那分组显示可能会不一样。按照年也会不一样。比如周:
一周登陆5次以下用户占比,5次~10次用户占比,10~20次占比
月:
月登陆10次以下用户占比,10次~20次用户占比,20~30次占比
年
年登陆50次以下用户占比,50次~100次用户占比,100~200次占比,200次以上占比试了试case when then 貌似不行,分组的部分根据统计结果会按照统计方式会发生变化。
有没有其它办法解决?
我想分组统计 一周登陆5次以下用户占比,5次~10次用户占比,10~20次占比如果我按照月统计,那分组显示可能会不一样。按照年也会不一样。比如周:
一周登陆5次以下用户占比,5次~10次用户占比,10~20次占比
月:
月登陆10次以下用户占比,10次~20次用户占比,20~30次占比
年
年登陆50次以下用户占比,50次~100次用户占比,100~200次占比,200次以上占比试了试case when then 貌似不行,分组的部分根据统计结果会按照统计方式会发生变化。
有没有其它办法解决?
select a/users, b/users, c/users
from(
select -- 用户总数和 3 个区间登录用户数
count(*) as users
, sum(case when data.times < b.a then 1 end) as a
, sum(case when data.times < b.b and data.times >=b.a then 1 end) as b
, sum(case when data.times > b.b then 1 end) as c
from(
-- 每个用户在指定时间段内(周/月/年)的登录次数
select user_id, count(*) as times
from table
where create_time between 'xx' and 'xx' -- **** 统计区间
group by user_id
) data,
(select 10 as a, 50 as b) b -- **** 定义 3 个统计区间: <a, <b and >=a, >b
) xx
mysql 数据库表 结构如下:CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`user_ip` char(20) NOT NULL,
`create_time` char(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;--
-- 转存表中的数据 `test`
--INSERT INTO `test` (`id`, `user_id`, `user_ip`, `create_time`) VALUES
(1, 11, '192.168.1.99', '2016-06-07 10:10:10'),
(2, 22, '192.168.1.100', '2016-06-07 10:20:10');
when cnt<=10 then '5次~10次'
when cnt<=20 then '10~20次'
else then '200次以'
end as c, count(*)
from (
select user_id, count(*) as cnt
from test
where create_time>CURDATE()-interval 7 day
group by user_id
) t
group by case when cnt<=5 then '5次以下'
when cnt<=10 then '5次~10次'
when cnt<=20 then '10~20次'
else then '200次以'
end
when cnt <3 then '3次以下'
when cnt <4 then '4次以下'
when cnt <5 then '5次以下'
else '5次以上' end as c, count(*)
from
(select user_ip, count(*) as cnt
from group_table
where create_time > CURDATE() -INTERVAL 7 DAY
GROUP BY user_ip) as t
GROUP BY cnt