Oracle查询以获取基于另一列的序列

ut6juiuv  于 2023-11-17  发布在  Oracle
关注(0)|答案(3)|浏览(89)

我试图在Oracle中构建一个查询,其中我有一个没有以下数据的表
| 秩序|数量|
| --|--|
| 34905 | 2 |
| 39754 | 5 |
输出结果应该如下所示
| 新序列|
| --|
| 34905-1|
| 34905-2|
| 39754-1|
| 39754-2|
| 小行星39754-3|
| 小行星39754-4|
| 小行星39754-5|
任何帮助将不胜感激。

wgeznvg7

wgeznvg71#

你有很多基于验证方式的变体:

with data(order_num, qty) as (
    select '34905', 2 from dual union all
    select '39754', 5 from dual
)
select order_num || '-' || level as newsequence
from data
connect by level <= qty and prior order_num = order_num 
    and prior sys_guid() is not null
;

with data(order_num, qty) as (
    select '34905', 2 from dual union all
    select '39754', 5 from dual
)
select order_num ||'-'|| column_value as new_sequence
from data,
lateral
(
    select level as column_value from dual
    connect by level <= qty
);

字符串
...

gzjq41n4

gzjq41n42#

你将需要一个域来生成序列。这里我使用了一个带有常量的cte,你可以使用1和max qty之间的递归cte(或者你有这样的数字表):

with num(n) as ( values (1),(2),(3),(4),(5)) 
select o.orderno || '-' || cast(num.n as varchar(2))
from num
join orders o
    on o.qty >= num.n
order by o.orderno, n;

字符串
Fiddle
使用数字表,如

insert into numbers (n)
select 1 from dual
union all
select 2 from dual
union all
select 3 from dual
union all
select 4 from dual
union all
select 5 from dual;


您可以将查询编写为:

select o.orderno || '-' || cast(numbers.n as varchar(2))
from numbers
join orders o
    on o.qty >= numbers.n
order by o.orderno, n;

ckocjqey

ckocjqey3#

这是某种类型的行生成器,正如你已经被告知的那样。在 * 较低 * Oracle数据库版本(我的意思是低于23c)中工作的版本是:
样本数据:

SQL> with test (c_order, qty) as
  2    (select 34905, 2 from dual union all
  3     select 39754, 5 from dual
  4    )

字符串
查询:

5  select c_order ||'-'|| column_value as new_sequence
  6  from test cross join
  7    table(cast(multiset(select level from dual
  8                        connect by level <= qty
  9                       ) as sys.odcinumberlist));

NEW_SEQUENCE
--------------------------------------------------------------------------------
34905-1
34905-2
39754-1
39754-2
39754-3
39754-4
39754-5

7 rows selected.

SQL>

相关问题