码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2020-06-10 15:58:29      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:sed   ast   select   int   eve   inter   require   fun   str1   

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

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

标签:sed   ast   select   int   eve   inter   require   fun   str1   

原文地址:https://www.cnblogs.com/-mrl/p/13085660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!