使用oracle SQL,我想生成一个数字字符串列表,这些数字最多可以计数到一个数量值。
Select [Item], [Quantity], <Something here> as [Quantity List]
from table
返回
[Item],[Quantity], [Quantity List]
'Socks', 2 , '1 2'
'Shoes', 3 , '1 2 3'
'Coats', 6 , '1 2 3 4 5 6'
'Hats' , 3 , '1 2 3' etc...
我不是想创建一个引用表,每个数量都需要评估,并在运行时放入适当的字符串提前感谢
我建议先生成所有数字,然后加入。您可以使用递归CTE:生成列表
with cte(n, max_qty, list) as (
select 1, max_qty, '1' as list
from (select max(quantity) as max_qty from t) x
union all
select n + 1, max_qty, list || ' ' || (n + 1)
from cte
where n < max_qty
)
select t.*, cte.list
from t join
cte
on t.quantity = cte.n;
这里有一个db<gt;不停摆弄
注意:如果您真的在使用SQL Server,那么您可以在该数据库中使用非常相似的逻辑。
您可以在select clause
的子查询中使用hiearchical query
,如下所示:
select item, quantity,
(select listagg(level, ' ') within group(order by level)
from dual connect by level <= quantity) as quantity_list
from t
Db<gt;争取同样的结果。