select g.CODE
, count(*)-1 as C_NO
, g.NAME
from MyTable as g
left join MyTable as o
on g.CODE = o.CODE
and g.NAME >= o.NAME
group by g.CODE
, g.NAME;
特定于 MySQL:
DELIMITER $$
CREATE PROCEDURE NumberRowsByGroup()
BEGIN
SET @code := 0;
SET @num := 0;
SELECT CODE, C_NO, NAME FROM
( select q.CODE
, q.NAME
, @num := IF(q.CODE = @code, @num + 1, 0) as C_NO
, @code := q.CODE as previous
from yourTable q
order by CODE
, NAME
) as p
;
END$$
DELIMITER ;