在SQL中按键键组顺序编号行?

时间:2011-03-28 18:28:39

标签: sql sequential

在SQL中是否有办法按密钥组依次添加行号

假设一个具有任意(CODE,NAME)元组的表。示例表:

CODE NAME    
---- ----
A    Apple
A    Angel
A    Arizona
B    Bravo
C    Charlie
C    Cat
D    Dog
D    Doppler
D    Data
D    Down

使用CODE作为分组属性的预期投影:

CODE C_NO NAME    
---- ---- ----
A    0    Apple
A    1    Angel
A    2    Arizona
B    0    Bravo
C    1    Charlie
C    0    Cat
D    0    Dog
D    1    Data
D    2    Down
D    3    Doppler

谢谢,

2 个答案:

答案 0 :(得分:30)

MySQL没有AFAIK。这涵盖了大多数基地..

SELECT
    CODE,
    ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO,
    NAME
FROM
    MyTable

答案 1 :(得分:3)

MySQL(可能还有大多数其他数据库):

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 ;

然后,我们可以致电:

CALL NumberRowsByGroup();

根据xaprb.com/blog帖子:how-to-number-rows-in-mysql,第二个更快。