在MySQL中,如何对类似的连续记录进行分组,使它们不被其他传送记录分隔
id | type |
1 | 1 |
2 | 1 |
3 | 1 |
4 | 5 |
5 | 1 |
6 | 8 |
7 | 1 |
8 | 3 |
9 | 3 |
10 | 3 |
结果应该是这样的:
id | type |
3 | 1 |
4 | 5 |
5 | 1 |
6 | 8 |
8 | 1 |
10 | 3 |
答案 0 :(得分:1)
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,type INT NOT NULL
,x INT NOT NULL
);
INSERT INTO my_table VALUES
(1,1,1),
(2,1,1),
(3,1,1),
(4,5,5),
(5,1,1),
(6,8,8),
(7,1,1),
(8,1,1);
SELECT MIN(c.id) id
, a.type
, a.x
FROM my_table a
LEFT
JOIN my_table b
ON b.id + 1 = a.id
AND b.type = a.type
AND b.x = a.x
LEFT
JOIN my_table c
ON c.id >= a.id
AND c.type = a.type
AND c.x = a.x
LEFT
JOIN my_table d
ON d.id - 1 = c.id
AND d.type = a.type
AND d.x = a.x
WHERE b.id IS NULL
AND c.id IS NOT NULL
AND d.id IS NULL
GROUP
BY a.id;
+------+------+---+
| id | type | x |
+------+------+---+
| 3 | 1 | 1 |
| 4 | 5 | 5 |
| 5 | 1 | 1 |
| 6 | 8 | 8 |
| 8 | 1 | 1 |
+------+------+---+
答案 1 :(得分:0)
您只需要一个标准组:
select count(*) id, type, `group`
from mytable
group by type, `group`
请注意,您需要分隔保留字" group"
答案 2 :(得分:0)
你的问题很不对劲。我认为以下可能接近你想要的。它通过分配标识连续组的新type
列,根据连续的grp
值标识组。
select type, max(id) as maxid, count(*) as numingroup
from (select t.*,
(@grp := if(@type = type, @grp, if(@type := type, @grp + 1, @grp + 1))) as grp
from my_table t cross join
(select @grp := 0, @type := -1)x
order by id
) t
group by grp, type;