我必须从所有行的表中选择值,如下所示:
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代码中。
答案 0 :(得分: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
是您从用户输入的字符串,可以包含一个或多个值(以逗号分隔)
BTW,使用带有绑定变量的预准备语句,不要只连接输入字符串 阅读更多here
答案 1 :(得分: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