Enumerate rows alphabetized in Oracle

我与影子孤独终老i 提交于 2020-01-05 11:09:40

问题


I wonder if this is possible in oracle to replace row number (we can use ROW_NUMBER() for example to get a digit) into alfabetical numbering

Let's say to get something like

NO | Name | Surname
================
A  | John | Doe
B  | Will | Doe
C  | Jim  | Wonder

instead of

NO | Name | Surname |
=================
1  | John | Doe
2  | Will | Doe
3  | Jim  | Wonder

I have an idea to create a variable like "ABCDEFG" and convert row number into correct SUBSTR, but this sounds a little unstable

Temporary solution for A-Z is to use

CHR((ROW_NUMBER() OVER (PARTITION BY SOMECOLUMN ORDER BY 1))+64)

回答1:


I created function that converts number to characters:

CREATE OR REPLACE FUNCTION num_to_char(p_number IN NUMBER)
RETURN VARCHAR2
IS
  v_tmp    NUMBER;
  v_result VARCHAR2(4000) := '';
BEGIN
  v_result := CHR(MOD(p_number - 1, 26) + 65);
  IF p_number > 26 THEN
    v_result := num_to_char(TRUNC((p_number-1)/26)) || v_result;
  END IF;
  RETURN v_result;
END num_to_char;
/

You can use it in selects:

SELECT num_to_char(ROW_NUMBER() OVER (PARTITION BY dummy ORDER BY 1))
FROM dual
CONNECT BY LEVEL < 3000

1 - A, 2 - B, ... , 25 - Y, 26 - Z, 27 - AA, 28 - AB, ..., 703 - AAA, 704 - AAB, ...



来源:https://stackoverflow.com/questions/29811299/enumerate-rows-alphabetized-in-oracle

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