-->

Enumerate rows alphabetized in Oracle

2019-08-13 18:24发布

问题:

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, ...