Mysql区间分组查询的实现方式

Thalia ·
更新时间:2024-09-20
· 1853 次阅读

目录

Mysql区间分组查询

场景

第一想法

一番百度之后

另一种解决办法

按区间分组查询、获取各区间的总数

数据表如下

需求

Mysql区间分组查询 场景

一张用户表(user),有用户id(id)、余额(balance)等字段,要求展示 余额在某个区间内的人数

​ 区间有0-1万,1-10万,10-50万,50-100万,100万+,

下面是模拟数据:

用户id        余额 1            100     2            200     3            3223 4            100001 5            100025 6            512123 7            565656 8            10000001

统计结果应该如下所示:

余额          人数
0-1万        1
1-10万        2
10-50万        1
50-100万    2
100万+        1

第一想法 select      count(if(balance between 0 and 10000, id , null ) ) as "0-1万",     count(if(balance between 10001 and 100000, id , null ) ) as "1-10万",     count(if(balance between 100001 and 500000, id , null ) ) as "10-50万",     count(if(balance between 500001 and 1000000, id , null ) ) as "50-100万",     count(if(balance > 1000000, id , null ) ) as "100万+" from user ;

这样可以查出来每个范围对应的人数,但是不尽人意,而且写的很麻烦…

一番百度之后 select interval(balance,0,10000,100000,500000,1000000) as i ,count(*)  from user group by i; select elt(interval(balance,0,10000,100000,500000,1000000),"0-1万","1-10万","10-50万","50-100万","100万+") as region ,count(*)  from user group by region;

利用了mysql提供的interval和elt函数实现了效果

interval

interval(N,N1,N2,N3) ,比较列表中的N值,该函数如果N<N1返回0,如果N<N2返回1,如果N<N3返回2 等等。

elt

elt(n,str1,str2,str3,…) 如果n=1,则返回str1,如果n=2,则返回str2,依次类推

两个函数结合,再加上group,实现了这种范围分组的效果

另一种解决办法

由于使用的是类似mysql语句查询的一个分析数据库,它不支持elt函数和interval函数(抄mysql没有抄全…)

实现这种范围分组的场景,可以通过创建中间表的形式实现。然后通过用户表去join

创建如下一个中间表:有下限、上限和区间名三个字段

lower        upper        region 0            10000        0-1万 10001        100000        1-10万 100001        500000        10-50万 500001        1000000        50-100万 1000000        2000000000    100万+

用户表就可以通过余额字段去join这个表

select region,count(*) from user  left join tmp on user.balance between tmp.lower and tmp.upper group by region 

就可以实现范围分组的效果

相比之前两种,感觉这个想法很有趣(同事教的)。

按区间分组查询、获取各区间的总数 数据表如下

需求

tick_count是次数、user_account是用户标识,user_account可能重复,统计0次,1-3次、4-6次、7-9次、10-12次、13次以上,这几个区间各有多少个用户数

select case when tc.stick_count = 0 then '0' when tc.stick_count > 0 and tc.stick_count <= 3 then '1to3' when tc.stick_count > 3 and tc.stick_count<= 6 then '4to6' when tc.stick_count > 6 and tc.stick_count <= 9 then '7to9' when tc.stick_count > 9 and tc.stick_count <= 12 then '10to12' when tc.stick_count > 13 then 'more13' end stickLevel, COUNT(DISTINCT user_account) total from t_stick_detail_hourly tc group by case when tc.stick_count = 0 then '0' when tc.stick_count > 0 and tc.stick_count <= 3 then '1to3' when tc.stick_count > 3 and tc.stick_count<= 6 then '4to6' when tc.stick_count > 6 and tc.stick_count <= 9 then '7to9' when tc.stick_count > 9 and tc.stick_count <= 12 then '10to12' when tc.stick_count > 13 then 'more13' end

运行结果

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



分组查询 分组 Mysql

需要 登录 后方可回复, 如果你还没有账号请 注册新账号