select
Id,request_id,key_skill_id,
ROW_NUMBER() OVER (PARTITION BY skill_id
ORDER BY request_id,skill_id) sequence
from report
where id= x
GROUP by request_id, skill_id
order by request_id,skill_id ;
I tried to write something like the following, but the result is not the same:
select
id,
request_id,
@skill_id :=skill_id as skill_id,
@row_number :=
CASE
WHEN @skill_id = skill_id THEN @row_number+1
ELSE 1
END AS row_number
from report,
(SELECT @row_number := 0, @skill_id := '') as t
where id =x
GROUP by request_id, skill_id
order by request_id, skill_id;
The original window function strikes me as a bit odd but I confess that I don't use these functions too frequently being confined to MySQL 5.7 myself. The
PARTITION BYclause specifies thekey_skill_idcolumn so re-numbering 1, 2, 3, etc. will be done on those rows with identicalkey_skill_idcolumn values. But then there is a finalORDERclause at the very end of the SQL that re-sorts the results so that rows with the samekey_skill_idwill not in general be together (unless, for example, there was only a single value offeedback_request_idbeing selected).To do the initial numbering the rows, however, the table must first be sorted by
key_skill_idand thenfeedback_request_id. The purpose of theGROUP BYclause in the original SQL is to function as an equivalent of aSELECT DISTINCTquery, which can't be used because the added row number column guarantees that each row is distinct. The reason why theGROUP BYworks is that it is applied before theROW_NUMBERwindow function is performed whereas theSELECT DISTINCTimplied filtering would be applied after theROW_NUMBERfunction is performed.Given you have provided no table definitions, data, expected output, etc. I was unable to test the following. This is my best guess: