Sequentially number rows by keyed group in SQL?

前端 未结 2 1171
野的像风
野的像风 2020-12-13 20:42

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:



        
相关标签:
2条回答
  • 2020-12-13 21:10
    • 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
    
    0 讨论(0)
  • 2020-12-13 21:18

    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.

    0 讨论(0)
提交回复
热议问题