我在oracle中有一个表值为5的表 我想将列的值更改为值数组,如[5,4,3,2,1] 表示差异为1
的值答案 0 :(得分:1)
这是“分层查询”的直接应用(如果不熟悉,请参阅Oracle文档)。它使用sys_connect_by_path
创建值列表(方括号在分层查询之外添加 - sys_connect_by_path
生成的前导逗号需要首先被切断,ltrim()
)。
with
test_data ( id, val ) as (
select 101, 5 from dual union all
select 103, 3 from dual
)
-- End of made-up test data; NOT part of the query.
-- SQL query begins BELOW THIS LINE. Change table and column names as needed.
select id, val,
'[' || ltrim(sys_connect_by_path(val - level + 1, ','), ',') || ']' as val_list
from test_data
where connect_by_isleaf = 1
connect by level <= val
and prior id = id
and prior sys_guid() is not null
;
ID VAL VAL_LIST
--- --- -----------
101 5 [5,4,3,2,1]
103 3 [3,2,1]
答案 1 :(得分:0)
对我来说,最简单的方法是为
创建功能CREATE OR REPLACE FUNCTION toArray (p_value NUMBER)
RETURN VARCHAR
AS
l_result VARCHAR (4000) := '[';
BEGIN
FOR i IN REVERSE 2 .. p_value
LOOP
l_result := l_result || i || ',';
END LOOP;
IF (p_value >= 1)
THEN
l_result := l_result || 1;
END IF;
l_result := l_result || ']';
RETURN l_result;
END;
查询select toArray(5) from dual
返回结果
[5,4,3,2,1]
答案 2 :(得分:0)
我建议使用一些更简单的方法。希望下面片段有帮助。 这里唯一的缺点我可以建议LISTAGG仅适用于oracle版本11及更高版本。所以它不适用于以下版本。
SELECT listagg(a.lvl, ',') within GROUP (
ORDER BY a.lvl DESC) somedata
from
(SELECT '&Enter_val'+1 - level lvl,
1 lvl2
from dual
CONNECT BY level < '&Enter_val'+1
ORDER BY lvl DESC
)a;