如何对后续行进行分组(基于条件),然后对它们进行计数[MySQL]? [英] How to group subsequent rows (based on a criteria) and then count them [MySQL]?

查看:124
本文介绍了如何对后续行进行分组(基于条件),然后对它们进行计数[MySQL]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的表(按日期排序):

  id |名称|类型| 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值和计数的后续行进行分组他们:

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

我在想写一个存储过程和使用游标,但我也想知道,如果有一个更简单的解决方案,例如使用嵌套的SELECT等。



我的问题非常类似于:如何对数组进行分组和计数,但是一个涉及PHP。

为了做到这一点,我使用了几个变量,
表结构,我创建了自己的测试,它是:

  create table abc(id int,name varchar(20),type int); 

insert into abc values
(1,'A',1),
(2,'A',2),
(3,'B' ,
(4,'A',1),
(5,'A',4),
(6,'A',5) / code>

查询结束是这样的:

 code> 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 a repeated,@ a:= name type from abc)as t group by repeated


b $ b

您可以看到它在 SQLFIDDLE 中有效,如果您有任何问题让我知道。



在SQLFIDDLE


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 | 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.

My question is very similar to: how to group array and count them, but that one concerns 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.

In the SQLFIDDLE

这篇关于如何对后续行进行分组(基于条件),然后对它们进行计数[MySQL]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆