0

我必须从表中的所有行中选择值,如下所示:

select distinct SCHM_CODE, 
       sum(DEP_AMT) as AMOUNT 
  from DLY_DEP_VIEW  
 where Schm_code in (select SCHM_CODE 
                       from DLY_DEP_VIEW )
 group by schm_code

我将从用户输入中获取输入,我不希望括号中的 select 语句,我需要为其中的所有内容返回一个值,例如:

select distinct SCHM_CODE, 
       sum(DEP_AMT) as AMOUNT 
  from DLY_DEP_VIEW  
 where Schm_code in (ALL_SCHM_CODES)
 group by schm_code

这是给我无效的标识符:(编辑)

select distinct SCHM_CODE, 
       sum(DEP_AMT) as AMOUNT 
  from DLY_DEP_VIEW  
 where Schm_code in (select regexp_substr('" + c + "', '[^,]+',1,level) p
          from dual t
       connect by level <= regexp_count('" + c + "', ',') + 1
)
 group by schm_code;

由于括号中的值在我的应用程序中不断变化。实现这一目标的最佳方法是什么?查询在 Java 代码中。

4

2 回答 2

1

你可以尝试这样的事情:

select distinct SCHM_CODE, 
       sum(DEP_AMT) as AMOUNT 
  from DLY_DEP_VIEW  
 where Schm_code in (select regexp_substr(:your_string, '[^,]+',1,level) p
          from dual t
       connect by level <= regexp_count(:your_string, ',') + 1
)
 group by schm_code

:your_string是您作为用户输入的字符串,可以包含一个或多个值(逗号分隔)

这是一个 sqlfiddle 演示

顺便说一句,使用带有绑定变量的准备好的语句,不要只是连接输入字符串。在这里
阅读更多

于 2012-11-28T15:25:45.220 回答
0

您可以使用嵌套表作为方法之一:

  • 创建嵌套表类型。假设是Schm_code数字数据类型。

    SQL> create or replace type t_list as table of number
      2  /
    
    Type created
    
  • 重写查询如下。如果列表是字符串列表,则列表的每个元素都必须用单引号引起来:

    select distinct SCHM_CODE, 
           sum(DEP_AMT) as AMOUNT 
      from DLY_DEP_VIEW  
      where Schm_code in (Select column_value
                            from table(t_list(<<your list of codes>>)))
      group by schm_code
    

在此示例中,为了演示,使用 Sql*plus 执行查询并手动输入元素:

SQL> select first_name
  2       , last_name
  3    from employees t
  4   where t.employee_id in (select column_value
  5                             from table(t_list(&list))
  6                           );
Enter value for list: 100,200
old   5:                            from table(t_list(&list))
new   5:                            from table(t_list(100,200))

FIRST_NAME           LAST_NAME                                                  
-------------------- -------------------------                                  
111                  King                                                       
Jennifer             Whalen                                                     

SQL> select first_name
  2       , last_name
  3    from employees t
  4   where t.employee_id in (select column_value
  5                             from table(t_list(&list))
  6                           );
Enter value for list: 110,300,220
old   5:                            from table(t_list(&list))
new   5:                            from table(t_list(110,300,220))

FIRST_NAME           LAST_NAME                                                  
-------------------- -------------------------                                  
John                 Chen  
于 2012-11-28T14:47:40.570 回答