假设我有这样一张表(按日期排序):
id | name | type | date
1 | A | 1 | 01-08-2012
2 | A | 2 | 01-08-2012
3 | B | 1 | 02-09-2012
4 | A | 1 | 01-10-2012
5 | A | 4 | 01-10-2012
6 | A | 5 | 02-10-2012
我想将具有相同“名称”值的后续行分组并计算它们:
name | count
A | 2
B | 1
A | 3
我正在考虑编写存储过程并使用游标,但我也在想,是否有更简单的解决方案,例如使用嵌套 SELECT 等。
我的问题非常类似于:how to group array and count them ,但那一个涉及 PHP。
最佳答案
为此我使用了几个变量, 表结构,我创建了自己的表结构只是为了测试,它是:
create table abc (id int, name varchar(20),type int);
insert into abc values
( 1 , 'A' , 1 ),
( 2 , 'A' , 2 ),
( 3 , 'B' , 1 ),
( 4 , 'A' , 1 ),
( 5 , 'A' , 4 ),
( 6 , 'A' , 5 )
查询结束是这样的:
set @a:='';
set @counter:=1;
set @groupby:=0;
select *,count(REPEATED) from (select name,if(@a=name,@counter:=@counter+1,@counter:=1) as rep,if(@counter=1,@groupby:=@groupby+1,@groupby) as repeated,@a:=name type from abc) as t group by repeated
您可以在 SQLFIDDLE 中看到它的工作原理如果您有任何问题,请告诉我。
在 SQLFIDDLE 中
关于mysql - 如何对后续行进行分组(基于条件)然后对它们进行计数[MySQL]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13566303/