mysql 根据某一列进行区间统计

南楼画角 提交于 2020-08-14 13:05:42

mysql中可以利用elt,interval函数来实现此类需求

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   
     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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!