Mysql - 如何将列的值分组为min-max范围?

时间:2015-06-12 10:20:53

标签: mysql

我可以将另一列的值分组为多个范围定义吗?

这是一个示例表:

mysql> select * from t;
+------+------+
| x    | y    |
+------+------+
|    1 |    1 |
|    2 |    1 |
|    3 |    1 |
|    4 |    2 |
|    5 |    2 |
|    6 |    2 |
|    7 |    1 |
|    8 |    1 |
|    9 |    1 |
+------+------+

我想选择以下信息:y=1的范围为x:1-3, 7-9y=2的范围为:4-6

定义和数据:

create table t (x int, y int);
insert into t(x,y) values (1,1),(2,1),(3,1),(4,2),(5,2),(6,2),(7,1),(8,1),(9,1);

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT y,group_concat(xr) FROM (
 SELECT y,
  CASE WHEN min(x)=max(x) THEN CAST(min(x) as char(8))
       ELSE concat(CAST(min(x) AS char(8)),'-',CAST(max(x) AS char(8)))
  END xr, g FROM (
  SELECT y,x, CASE WHEN @g=@c AND x=@l+1
                   THEN @g ELSE @c:=@g:=@g+1 END g ,
         @l:=x  lastx 
  FROM tab,( SELECT @g:=0, @c:=-1, @l=-1 ) vars
  ORDER BY y,x
 ) grp1
 GROUP BY y,g
) grp2 GROUP BY y

使用的变量:

@g  group counter
@c  current x value
@l  previous ('last') x value

我还修复了每组问题的单项。

请看这里的工作小提琴:http://www.sqlfiddle.com/#!9/cc836/2

答案 1 :(得分:1)

如果x是一个连续的序列(没有间隙),那么你可以这样做:

SELECT a.y
     , a start
     , MIN(c.x) end 
  FROM t a
  LEFT 
  JOIN t b 
    ON b.y = x.y
   AND b.x = a.x - 1
  LEFT 
  JOIN tbl c 
    ON c.y = a.y
   AND c.x >= a.x
  LEFT 
  JOIN t d 
    ON d.y = a.y
   AND d.x = c.x + 1
 WHERE b.x IS NULL 
   AND c.x IS NOT NULL
   AND d.x IS NULL
 GROUP 
    BY a.y,a.x; 

http://www.sqlfiddle.com/#!9/26aef/33

如果不是,那么你可以这样做:

SELECT a.y
     , a.x start
     , MIN(c.x) end 
  FROM (SELECT *,@a:=@a+1 rank FROM t,(SELECT @a:=0) vars ORDER BY x) a
  LEFT 
  JOIN (SELECT *,@b:=@b+1 rank FROM t,(SELECT @b:=0) vars ORDER BY x) b 
    ON b.y = a.y
   AND b.rank = a.rank - 1
  LEFT 
  JOIN (SELECT *,@c:=@c+1 rank FROM t,(SELECT @c:=0) vars ORDER BY x) c 
    ON c.y = a.y
   AND c.rank >= a.rank
  LEFT 
  JOIN (SELECT *,@d:=@d+1 rank FROM t,(SELECT @d:=0) vars ORDER BY x) d 
    ON d.y = a.y
   AND d.rank = c.rank + 1
 WHERE b.x IS NULL 
   AND c.x IS NOT NULL
   AND d.x IS NULL
 GROUP 
    BY a.y,a.x; 

http://www.sqlfiddle.com/#!9/26aef/54

但是,对于较大的数据集,这两个查询都会很慢。也就是说,第二个解决方案中包含的想法可以适用于性能问题的情况 - 好吧,类似于cars10的解决方案。