[英]How to group subsequent rows (based on a criteria) and then count them [MySQL]?
假設我有這樣一張桌子(按日期排序):
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”值的后續行進行分組並對它們進行計數:
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' , 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中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.