zoukankan      html  css  js  c++  java
  • mysql 根据某一列进行区间统计

    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 yb_level;
    +-----------+-----+
    | 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 yb_level;
    +-------------+-----+
    | 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
  • 相关阅读:
    shell 基础进阶 *金字塔
    shell,awk两种方法写9*9乘法表
    shell脚本判断一个用户是否登录成功
    shell 冒泡算法 解决数组排序问题
    shell 石头剪刀布
    应用shell (ssh)远程链接主机
    nmcli命令使用
    光盘yum源autofs按需挂载
    LVM扩容,删除
    LVM创建
  • 原文地址:https://www.cnblogs.com/-mrl/p/13085660.html
Copyright © 2011-2022 走看看