Sayangnya, MySQL tidak memiliki fungsi windowing yang Anda perlukan. Jadi, Anda harus menggunakan sesuatu seperti ini:
Kueri Terakhir
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:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
) x
order by overall_row_num
lihat SQL Fiddle dengan Demo
Penjelasan:
Pertama, pilih dalam, ini menerapkan row_number
tiruan ke semua catatan di tabel Anda (Lihat SQL Fiddle dengan Demo
):
select data, @rn:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
Bagian kedua dari kueri, bandingkan setiap baris di tabel Anda dengan baris berikutnya untuk melihat apakah nilainya sama, jika tidak, mulailah group_row_number
lebih (lihat SQL Fiddle dengan 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:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
Pilihan terakhir, mengembalikan nilai yang Anda inginkan dan menempatkannya kembali dalam urutan yang Anda minta:
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:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
) x
order by overall_row_num