MySQL:按二进制变量的和对行进行分组

MySQL:按二进制变量的和对行进行分组,mysql,group-by,Mysql,Group By,我有一个表,我想用一个二进制变量group\u generator对其进行分组,该变量定义了组的结尾:如果它等于1,则该组包含group\u generator=0 例如: Numbers group_generator 10 0 20 0 30 1 40 0 50 1 60 1 我需要将数字分为

我有一个表,我想用一个二进制变量
group\u generator
对其进行分组,该变量定义了组的结尾:如果它等于
1
,则该组包含
group\u generator=0

例如:

Numbers        group_generator    
10             0    
20             0    
30             1    
40             0    
50             1 
60             1
我需要将数字分为三组:

(10, 20, 30); 
(40, 50); 
(60)
我尝试为索引小于当前值的所有行创建一个总和为
group\u generator
的新列,如下所示:

Numbers        group_generator    group
10             0                  0
20             0                  0
30             1                  0
40             0                  1
50             1                  1
60             1                  2
并按最后一列进行分组,但如果没有临时表,这很复杂


在MySQL中有没有一种简单的方法可以做到这一点?

一旦您有了新的列,此查询将为您提供所需的结果:

SELECT GROUP_CONCAT(Numbers) FROM table GROUP BY `group`
输出:

group_concat(numbers)
10,20,30
40,50
60
因此,整个查询可以是:

SELECT GROUP_CONCAT(Numbers),
(SELECT IFNULL(SUM(group_generator), 0) FROM table1 t2 WHERE t2.id < table1.id) AS `group`
FROM table1
GROUP BY `group`
您还可以使用存储过程生成此输出:

DELIMITER //
drop PROCEDURE if EXISTS groupit
//
create procedure groupit()
begin
   declare num int;
   declare numgroup varchar(1024) default '';
   declare gnum int default 0;
   declare pid int default 1;
   declare gg int;

   DECLARE CONTINUE HANDLER FOR NOT FOUND SET gg = -1;

   repeat
     select group_generator, Numbers  into gg, num from table2 where id=pid;
     if (gg >= 0) then
         set numgroup = concat(numgroup, if(numgroup='', '', ','), num);
         if (gg = 1) then
             select numgroup, gnum;
             set numgroup = '';
             set gnum = gnum + 1;
         end if;
     end if;
     set pid=pid+1;
   until gg = -1
   end repeat;
end
//
delimiter ;

你的问题不清楚。。更好地解释“索引小于当前值的所有行”这是什么意思?您是否有可以识别当前和<当前的列,例如自动增量id字段?谢谢!这几乎解决了我的全部问题。但是,如果您有一个不想重复两次的复杂表达式(并且您不能使用临时表存储该表),而不是
table1
,您将如何计算
SUM(group\u generator)
?临时表肯定是最好的,重复该表达式,尽管凌乱可以工作,是否可以使用联接?我会考虑一下……我想根据定义,联接将导致表1被引用的次数超过1次,所以这可能也不起作用。您可以使用存储过程吗?我在回答中举了个例子,太好了。我担心如果您不能使用临时表,您可能也不能使用存储过程。
DELIMITER //
drop PROCEDURE if EXISTS groupit
//
create procedure groupit()
begin
   declare num int;
   declare numgroup varchar(1024) default '';
   declare gnum int default 0;
   declare pid int default 1;
   declare gg int;

   DECLARE CONTINUE HANDLER FOR NOT FOUND SET gg = -1;

   repeat
     select group_generator, Numbers  into gg, num from table2 where id=pid;
     if (gg >= 0) then
         set numgroup = concat(numgroup, if(numgroup='', '', ','), num);
         if (gg = 1) then
             select numgroup, gnum;
             set numgroup = '';
             set gnum = gnum + 1;
         end if;
     end if;
     set pid=pid+1;
   until gg = -1
   end repeat;
end
//
delimiter ;