一张用户表(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(N,N1,N2,N3) ,比较列表中的N值,该函数如果N elt(n,str1,str2,str3,…) 如果n=1,则返回str1,如果n=2,则返回str2,依次类推 两个函数结合,再加上group,实现了这种范围分组的效果 由于使用的是类似mysql语句查询的一个分析数据库,它不支持elt函数和interval函数(抄mysql没有抄全…) 实现这种范围分组的场景,可以通过创建中间表的形式实现。然后通过用户表去join 创建如下一个中间表:有下限、上限和区间名三个字段 用户表就可以通过余额字段去join这个表 就可以实现范围分组的效果 相比之前两种,感觉这个想法很有趣(同事教的)。 打怪升级!upup!elt
另一种解决办法
lower upper region
0 10000 0-1万
10001 100000 1-10万
100001 500000 10-50万
500001 1000000 50-100万
1000000 2000000000 100万+
select region,count(*)
from user
left join tmp on user.balance between tmp.lower and tmp.upper
group by region