如何将多行分组并连接成20s的组

时间:2012-05-30 00:26:50

标签: mysql sql group-by concatenation break

我有一张只有数字ID的表

ID
1
2
3
4
5
6
7
8
9
10

我想打破并将这些ID连接(分组)为5s或20s的组,ej。

GROUPS
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15

如何使用SQL执行此操作?

更新

使用已排序的ID进行选择

  SELECT GROUP_CONCAT(id ORDER BY id) AS GROUPS
  FROM `test`
  GROUP BY (id - 1) DIV 5

结果:

  GROUPS
  1,2,3,4,5
  6,7,8,9,10
  11,12,13,14,15
  16,17,18,19,20
  21,22,23,24,25
  26,27,28,29,30
  31,32,33,34,35

选择第二个未排序的表

  SELECT GROUP_CONCAT(id ORDER BY id) AS GROUPS
  FROM `test2`
  GROUP BY (id - 1) DIV 5

结果:

  GROUPS
  3,5
  10
  12
  16
  23,24,25
  32,35
  43,44
  47
  55
  61
  68,70
  77
  84
  89
  91,92,95
  97,100

2 个答案:

答案 0 :(得分:3)

对于MySQL:

SELECT GROUP_CONCAT(id ORDER BY id) AS GROUPS
FROM yourtable
GROUP BY (id - 1) DIV 5

查看在线工作:sqlfiddle

答案 1 :(得分:2)

对于未分类的ID:

SET @rank=0;
SELECT
    id,
    @rank:=@rank+1 AS rank,
    GROUP_CONCAT(id ORDER BY id) AS GROUPS
FROM  `test2`
GROUP BY (@rank ) DIV 5

结果:

+----+------+----------------+
| id | rank | GROUPS         |
+----+------+----------------+
|  1 |    1 | 1,3,5,7,9      |
| 13 |    7 | 11,13,15,17,19 |
| 29 |   15 | 21,23,25,27,29 |
| 31 |   16 | 31,33,35,37,39 |
| 45 |   23 | 41,43,45,47,49 |
| 51 |   26 | 51,53,55,57,59 |
| 61 |   31 | 61,63,65,67,69 |
| 77 |   39 | 71,73,75,77,79 |
| 81 |   41 | 81,83,85,87,89 |
| 93 |   47 | 91,93,95,97,99 |
+----+------+----------------+

非常感谢你的帮助,没有你的帮助,我无法知道!