贝壳的程序员日子

导航

mysql 按区间group by

在统计需求中 有时往往需要对区间进行分组
 
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   
    -> 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

posted on 2013-12-06 12:02  roland1982  阅读(2276)  评论(0编辑  收藏  举报