如何在oracle sql中生成2个值之间的字母?
How to generate alphabetic letters between 2 values in oracle sql?
select 'V4A-V4G' 来自双重;
sample output:
V4A
V4B
V4C
V4D
V4E
V4G
select 'R8M-R8S' 来自双重;
sample output:
R8M
R8N
R8O
R8P
R8Q
R8R
R8S
这是一个选项:对于您发布的示例数据(我将它们放入同一个 test
CTE),找到第 3 个和最后一个字母的 ASCII 代码(正如您在评论中所说的那样,它们仅使用)并进行一些行生成器计算。
SQL> with test (id, col) as
2 (select 1, 'V4A-V4G' from dual union all
3 select 2, 'R8M-R8S' from dual
4 )
5 select id,
6 substr(col, 1, 2) || chr(ascii(substr(col, 3, 1)) + column_value - 1) val
7 from test cross join
8 table(cast(multiset(select level from dual
9 connect by level <= ascii(substr(col, -1)) - ascii(substr(col, 3, 1)) + 1
10 ) as sys.odcinumberlist))
11 order by id, val;
ID VAL
---------- ---
1 V4A
1 V4B
1 V4C
1 V4D
1 V4E
1 V4F
1 V4G
2 R8M
2 R8N
2 R8O
2 R8P
2 R8Q
2 R8R
2 R8S
14 rows selected.
SQL>
更直接的方式(避免CONNECT BY
过程):
with
test (id, col) as (
select 1, 'V4A-V4G' from dual union all
select 2, 'R8M-R8S' from dual
)
select id, substr(col, 1, 2) || column_value as val
from test join sys.odcivarchar2list('A','B','C','D','E','F','G','H','I',
'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
on column_value between substr(col, 3, 1) and substr(col, 7, 1)
order by id, val -- if needed
;
当然,如果您需要经常这样做,您可以使用实际的 table,其中包含一列和 26 行的大写字母,这样您就不需要在运行中创建它每个使用它的查询(以及每次使用查询)。这将使查询更加简单。
注意 - 在较旧的 Oracle 版本中,您可能需要将 sys.odci...list
包装在 table( ... )
.
中
select 'V4A-V4G' 来自双重;
sample output:
V4A
V4B
V4C
V4D
V4E
V4G
select 'R8M-R8S' 来自双重;
sample output:
R8M
R8N
R8O
R8P
R8Q
R8R
R8S
这是一个选项:对于您发布的示例数据(我将它们放入同一个 test
CTE),找到第 3 个和最后一个字母的 ASCII 代码(正如您在评论中所说的那样,它们仅使用)并进行一些行生成器计算。
SQL> with test (id, col) as
2 (select 1, 'V4A-V4G' from dual union all
3 select 2, 'R8M-R8S' from dual
4 )
5 select id,
6 substr(col, 1, 2) || chr(ascii(substr(col, 3, 1)) + column_value - 1) val
7 from test cross join
8 table(cast(multiset(select level from dual
9 connect by level <= ascii(substr(col, -1)) - ascii(substr(col, 3, 1)) + 1
10 ) as sys.odcinumberlist))
11 order by id, val;
ID VAL
---------- ---
1 V4A
1 V4B
1 V4C
1 V4D
1 V4E
1 V4F
1 V4G
2 R8M
2 R8N
2 R8O
2 R8P
2 R8Q
2 R8R
2 R8S
14 rows selected.
SQL>
更直接的方式(避免CONNECT BY
过程):
with
test (id, col) as (
select 1, 'V4A-V4G' from dual union all
select 2, 'R8M-R8S' from dual
)
select id, substr(col, 1, 2) || column_value as val
from test join sys.odcivarchar2list('A','B','C','D','E','F','G','H','I',
'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
on column_value between substr(col, 3, 1) and substr(col, 7, 1)
order by id, val -- if needed
;
当然,如果您需要经常这样做,您可以使用实际的 table,其中包含一列和 26 行的大写字母,这样您就不需要在运行中创建它每个使用它的查询(以及每次使用查询)。这将使查询更加简单。
注意 - 在较旧的 Oracle 版本中,您可能需要将 sys.odci...list
包装在 table( ... )
.