mysql区间范围分组_mysql按区间groupby
在统计需求中 有时往往需要对区间进⾏分组
mysql中可以利⽤elt函数来实现此类需求
mysql> select * from k1;
+------+------+
| id | yb |
+------+------+
| 1 | 100 |
| 2 | 11 |
| 3 | 5 |
| 4 | 501 |
| 5 | 1501 |
| 6 | 1 |
+------+------+
现在要进⾏统计,⼩于100的,100~500的,500~1000的,1000以上的,这各个区间的id数
利⽤interval划出4个区间
再利⽤elt函数将4个区间分别返回⼀个列名
mysql> select elt(interval(d.yb,0, 100, 500, 1000), 'less100', '100to500', '500to1000', 'more1000') as yb_level, count(d.id) as cnt
-> from k1 d
-> group by elt(interval(d.yb, 0, 100, 500, 1000), 'less100', '100to500', '500to1000', 'more1000K');
+-----------+-----+
| yb_level | cnt |
+-----------+-----+
| 100to500 | 1 |
| 500to1000 | 1 |
| less100 | 3 |
| more1000 | 1 |
+-----------+-----+
4 rows in set (0.00 sec)
如果需要按从⼩到⼤排序的话 可以在列名定义时稍加⼀个⾸字符 对各档区间进⾏排序
mysql> select elt(interval(d.yb,0, 100, 500, 1000), '1/less100', '2/100to500', '3/500to1000', '4/more1000') as yb_level, count(d.id) as cnt
-> from k1 d
groupby分组-
> group by elt(interval(d.yb, 0, 100, 500, 1000), '1/less100', '2/100to500', '3/500to1000', '4/more1000K');
+-------------+-----+
| yb_level | cnt |
+-------------+-----+
| 1/less100 | 3 |
| 2/100to500 | 1 |
| 3/500to1000 | 1 |
| 4/more1000 | 1 |
+-------------+-----+
4 rows in set (0.00 sec)
附elt函数格式:
ELT(N,str1,str2,str3,...)
如果N= 1,返回str1,如果N= 2,返回str2,等等。如果N⼩于1或⼤于参数个数,返回NULL。ELT()是FIELD()反运算。
mysql> select ELT(1, 'ej', 'Heja', 'hej', 'foo');
-> 'ej'
mysql> select ELT(4, 'ej', 'Heja', 'hej', 'foo');
-> 'foo'
interval函数格式:
INTERVAL()Return the index of the argument that is less than the first argument(⼩于后⾯的某个参数,就返回这个参数的前⼀个位置数字)
INTERVAL(N,N1,N2,N3,...)
Returns 0 if N < N1, 1 if N < N2 and so on or -1 if N is NULL. All arguments are treated as integers. It
is required that N1 <
N2 < N3 < ... < Nn for this function to work correctly. This is because a binary search is used (very fast).
mysql> SELECT INTERVAL(23, 1, 15, 17, 30, 44, 200); (23⼩于30,30的位置是4,于是返回3)
-> 3
mysql> SELECT INTERVAL(10, 1, 10, 100, 1000);
-> 2
mysql> SELECT INTERVAL(22, 23, 30, 44, 200);
-> 0
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论