MySQL har desværre ikke vinduesfunktioner, hvilket er hvad du skal bruge. Så du bliver nødt til at bruge noget som dette:
Endelig forespørgsel
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
Forklaring:
Først, indre markering, dette anvender et falsk row_number
til alle posterne i din tabel (se SQL Fiddle with Demo
):
select data, @rn:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
Anden del af forespørgslen, sammenligner hver række i din tabel med den næste for at se, om den har samme værdi, hvis den ikke starter, så starter group_row_number
over (se 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:[email protected]+1 overall_row_num
from yourtable, (SELECT @rn:=0) r
) x
order by data, overall_row_num
Det sidste valg returnerer de værdier, du ønsker, og placerer dem tilbage i den rækkefølge, du anmodede om:
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