Sequentially number rows by keyed group in SQL?

折月煮酒 提交于 2019-12-17 23:23:51

问题


Is there a way in SQL to sequentially add a row number by key group?

Assume a table with arbitrary (CODE,NAME) tuples. Example table:

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

Desired projection using CODE as the grouping attribute:

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

Thanks,


回答1:


  • SQL Server
  • Oracle
  • Postgres
  • Sybase

MySQL doesn't AFAIK. This covers most bases..

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



回答2:


MySQL (and probably most other databases):

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;

Specific to 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 ;

Then, we can call:

CALL NumberRowsByGroup();

According to xaprb.com/blog post: how-to-number-rows-in-mysql, the second is faster.



来源:https://stackoverflow.com/questions/5463384/sequentially-number-rows-by-keyed-group-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!