Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oracle/SQL-需要从每行的字符串中选择最大值的查询_Sql_Oracle - Fatal编程技术网

Oracle/SQL-需要从每行的字符串中选择最大值的查询

Oracle/SQL-需要从每行的字符串中选择最大值的查询,sql,oracle,Sql,Oracle,我需要一种优雅的方式从包含逗号分隔列表的字段中选择最大值 Expected Values: List_1 | Last ------ | ------ A,B,C | C B,D,C | D 我正在使用下面的查询,但没有得到预期的结果 select list_1, ( select max(values) WITHIN GROUP (order by 1) from ( select regexp_s

我需要一种优雅的方式从包含逗号分隔列表的字段中选择最大值

Expected Values:

List_1 | Last
------ | ------
A,B,C  | C   
B,D,C  | D 
我正在使用下面的查询,但没有得到预期的结果

select
   list_1,
   (
      select max(values) WITHIN GROUP (order by 1) 
      from (
         select
            regexp_substr(list_1,'[^,]+', 1, level) as values
         from dual
         connect by regexp_substr(list_1, '[^,]+', 1, level) is not null)
   ) as last
from my_table

有人有办法修复我的查询吗?

请只标记您真正使用的数据库。该表不是第一个标准格式,因此要求以“优雅”的方式处理它可能是一厢情愿的想法……这是表中仅有的两列,还是您还有另一列可以唯一标识每一行?可以动态添加,但如果数据中已经存在,为什么不使用它并节省一些执行时间?@mathguy这不是我的完整查询,但我在表中有一个唯一的标识符。@mathguy我基本上不想创建一个脚本,该脚本将循环遍历每一行以提取我想要的信息
with
     test_data ( id, list_1 ) as (
       select 101, 'A,B,C' from dual union all
       select 102, 'B,D,C' from dual union all
       select 105, null    from dual union all
       select 122, 'A'     from dual union all
       select 140, 'A,B,B' from dual
     )
-- end of simulated table (for testing purposes only, not part of the solution)
select   id, list_1, max(token) as max_value
from     ( select id, list_1, 
                  regexp_substr(list_1, '([^,])(,|$)', 1, level, null, 1) as token
           from   test_data
           connect by level <= 1 + regexp_count(list_1, ',')                  
                  and prior id = id
                  and prior sys_guid() is not null
         )
group by id, list_1
order by id
;

  ID LIST_1_ MAX_VAL
---- ------- -------
 101 A,B,C   C    
 102 B,D,C   D    
 105            
 122 A       A    
 140 A,B,B   B  
select   d.id, d.list_1, x.max_value
from     test_data d,
         lateral ( select max(regexp_substr(list_1, '([^,]*)(,|$)',
                                            1, level, null, 1)) as max_value
                   from   test_data x
                   where  x.id = d.id
                   connect by level <= 1 + regexp_count(list_1, ',')
                 ) x
order by d.id
;