不幸的是,MySQL 没有您需要的窗口函数。所以你将不得不使用这样的东西:
最终查询
select data, group_row_number, overall_row_num
from
(
select data,
@num := if(@data = `data`, @num + 1, 1) as group_row_number,
@data := `data` as dummy, overall_row_num
from
(
select data, @rn:=@rn+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
) x
order by overall_row_num
见SQL Fiddle with Demo
解释:
首先,内部选择,这将模拟应用于row_number
表中的所有记录(参见SQL Fiddle with Demo):
select data, @rn:=@rn+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
查询的第二部分,将表中的每一行与下一行进行比较,看它是否具有相同的值,如果没有,则重新开始group_row_number
(参见SQL Fiddle with Demo):
select data,
@num := if(@data = `data`, @num + 1, 1) as group_row_number,
@data := `data` as dummy, overall_row_num
from
(
select data, @rn:=@rn+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
最后一个选择,返回您想要的值并将它们按您请求的顺序放回:
select data, group_row_number, overall_row_num
from
(
select data,
@num := if(@data = `data`, @num + 1, 1) as group_row_number,
@data := `data` as dummy, overall_row_num
from
(
select data, @rn:=@rn+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
) x
order by overall_row_num