简体   繁体   English

如何对后续行进行分组(基于标准)然后对它们进行计数[MySQL]?

[英]How to group subsequent rows (based on a criteria) and then count them [MySQL]?

Let's say I have such a table (ordered by date): 假设我有这样一张桌子(按日期排序):

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

I want to group subsequent rows that have the same 'name' value and count them: 我想对具有相同“name”值的后续行进行分组并对它们进行计数:

name | count 
A    | 2
B    | 1
A    | 3

I was thinking about writing a stored procedure and using cursors, but I was also wondering, if there's a simpler solution, for example using nested SELECTs, etc. 我正在考虑编写存储过程和使用游标,但我也想知道,如果有一个更简单的解决方案,例如使用嵌套的SELECT等。

My question is very similar to: how to group array and count them , but that one concerns PHP. 我的问题非常类似于: 如何对数组进行分组并对它们进行计数 ,但这个问题与PHP有关。

To do that I used a couple of variables, the table structure, I created my own just for testing and it's: 为此,我使用了几个变量,表结构,我创建了自己的仅用于测试,它是:

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  )

the query ended being like this: 查询结束如下:

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

you can see it works in SQLFIDDLE if you have any question let me know. 如果您有任何疑问,请告诉我,您可以看到它在SQLFIDDLE有效

In the SQLFIDDLE 在SQLFIDDLE中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM