ORA-00913: too many values while using case when

不羁的心 提交于 2021-01-28 12:09:23

问题


I have a requirement such that, if one condition is true i should execute on query Q1 if that condition fails, i should execute another query Q2. This queries result is the records of search performed by the user. I am using case when statement for if condition, as Q1 and Q2 have more than one column to retrieve, I am getting ORA-00913: too many values . I came to know that case when cannot execute queries with more columns in retrieving data. Can anyone suggest how to achieve this type requirement.

Update :

I cannot give exact query, but can provide pseudo code

select case when c1='1' then 
select c1,c2,c3 from table1
else select c1,c2,c3 from table2  end
from table1;

Here iam giving sample data.

Table1

C1      C2     C3
1       null    1
1       2       null

Table2

C1      C2     C3
1       4       1
1       3       5
2       9       null

When i run query you provided, the output will be as below.

select
    coalesce(table2.c1, table1.c1) c1,
    coalesce(table2.c2, table1.c2) c2,
    coalesce(table2.c3, table1.c3) c3
from table1
    left outer join table2
       on (your keys here)
           and table1.c1 <> '1' -- This gets table1 if c1 = '1';

Output:

C1    C2    C3
1     4      1
1     2      5
2     9      null

But what iam expecting the output is

C1    C2    C3
1     null   1
1     2      null
2     9      null

Hope i explained clearly.


回答1:


When you use a case, you must return only a single record - not more than 1. To achieve your desired result, I would use a left outer join (assuming you have a way to join table1 to table2), but add your check on table1.c1 into the join condition so that table2 values would only be present if c1 <> '1'

select
    coalesce(table2.c1, table1.c1) c1,
    coalesce(table2.c2, table1.c2) c2,
    coalesce(table2.c3, table1.c3) c3
from table1
    left outer join table2
       on (your keys here)
           and table1.c1 <> '1' -- This gets table1 if c1 = '1';

This solution assumes table1 and table2 relates. If you can't relate them, then it sounds almost like you can use a union all in which you take all the values from table1 where c1 = '1' and union those to all table2 rows. If necessary, you could only include table2 values if c1 <> '1'.

select c1, c2, c3 from table1 where c1 = '1'
union all
select c1, c2, c3 from table2; -- where c1 <> '1' -- if necessary

UPDATE

Based on your sample data and expected output, please use the second query above:

select c1, c2, c3 from table1 where c1 = '1'
union all
select c1, c2, c3 from table2 where c1 <> '1'

SQL Fiddle: http://www.sqlfiddle.com/#!4/710f0/1/0



来源:https://stackoverflow.com/questions/29069199/ora-00913-too-many-values-while-using-case-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!