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

发布于 2024-10-28 03:06:09 字数 503 浏览 4 评论 0原文

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

谢谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浮光之海 2024-11-04 03:06:09

这涵盖了大多数基础。

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

This covers most bases.

SELECT
    CODE,
    ROW_NUMBER() OVER (PARTITION BY CODE ORDER BY NAME) - 1 As C_NO,
    NAME
FROM
    MyTable
半世晨晓 2024-11-04 03:06:09

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,第二个更快。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文