View with case expression in where statement
Hello,
I want to create a view like:
create or replace view oferte_la_culegere_vw(pcod_lucrare varchar2, pcod_tipprodso varchar2) is
select ol.cod_oferta from oferte_lucrare ol
join oferte o on o.cod_oferta = ol.cod_oferta
where ol.cod_tip_lucrare = pcod_lucrare
and (ol.activ = 'D' or
case when ol.activ = 'I' then
if os_util.are_atributie(o.atributie_exceptie) then ... -- add condition or ol.activ = 'N' to the query
intersect
select t.cod_oferta from tipinstprodso_oferta
where t.cod_tipprodso = pcod_tipprodso
order by 1;
show errors view oferte_la_culegere_vw;So in the 1st select i have to filter only for ol.activ = 'D', but i can select records with ol.activ = 'N', only if that condition matches (os_util.are_atributie...).
How can i specify this in a view?
Thanks
Dear,
If I have clearly undestood your requirement you could do this
select ol.cod_oferta from oferte_lucrare ol
join oferte o on o.cod_oferta = ol.cod_oferta
where ol.cod_tip_lucrare = pcod_lucrare
and (ol.activ = 'D'
OR(ol.activ = 'N'
AND CASE WHEN ol.activ = 'I'
THEN os_util.are_atributie(o.atributie_exceptie
ELSE
END = 'xxxx'
Best Regards
Mohamed Houri
Similar Messages
-
Error creating view with CASE -- WHEN statement in SQL*Plus
I am using Oracle 8i 8.1.7
I have an Oracle view which uses CASE...WHEN statements.
The view compiles fine in DBA studio.
Using TOAD I saved the view as an *.sql file.
However, when I try to create the view in SQL*Plus I get the following error:
SP2-0734: unknown command beginning "CASE WHEN ..." - rest of line ignored.
According to the documentation CASE -- WHEN has been implemented since since Oracle 8i rel. 2 (8.1.6)Well I'm using 8.1.6.3 and CASE and DECODE both work for me:
SQL> create or replace view v_accs as select account_name, txn,
2 decode(credit, 0, 'DB', 'CR') t_type
3 from accs;
View created.
SQL> select * from v_accs;
ACCOUNT_NA TXN T_
APC 1 DB
ABC 2 DB
HJJ 3 DB
HJH 4 CR
HJK 5 CR
APC 6 DB
APC 7 DB
ABC 8 DB
ABC 9 DB
HJJ 10 DB
HJJ 11 DB
HJH 12 DB
HJH 13 DB
HJK 14 DB
HJK 15 CR
15 rows selected.
SQL> create or replace view v_accs as select account_name, txn,
2 case when credit = 0 then 'DB' else 'CR'end as t_type
3* from accs
View created.
SQL> select * from v_accs;
ACCOUNT_NA TXN T_
APC 1 DB
ABC 2 DB
HJJ 3 DB
HJH 4 CR
HJK 5 CR
APC 6 DB
APC 7 DB
ABC 8 DB
ABC 9 DB
HJJ 10 DB
HJJ 11 DB
HJH 12 DB
HJH 13 DB
HJK 14 DB
HJK 15 CR
15 rows selected.
SQL>
rgds, APC -
How to use the CASE Expression in Where Cluase?
Hi All,
I'm trying to use the CASE Expression in the Where Clause at some trigger on the Form?
I've tried this Code:
Declare
N Number;
begin
SELECT COUNT(E.EMP_SID)
INTO N
FROM EMPLOYEES E, RANKS R
WHERE CASE WHEN R.qualification_sid = 1104 AND E.rank_sid = 8 THEN
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1)
ELSE
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1)
END
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR');
END;
When I run this code as a normal query at any SQL editor it works successfully, But When I Compile it at some trigger on the Form it gives me this error:
Encountered the symbol "CASE" when expecting one of the following:
( - + mod ......
Heeey how to specify the previous code to be shown as code in the thread?
Note: I'm using Forms 6iOK I tried it and worked but for one condition:
WHERE DECODE (E.qualification_sid, 1104,
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1))
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR')
But how to put two conditions for the same Expression:
WHERE DECODE ((E.qualification_sid, 1104) AND (E.RANK_SID, 8),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.spe_per)+1),
(TO_DATE(E.RANK_DATE, 'DD-MM-RR')+(365*M.mili_yea_per)+1))
BETWEEN TO_DATE('01-07-2011', 'DD-MM-RR') AND TO_DATE('31-07-2011', 'DD-MM-RR')
The previous code gives me this error: missing right parenthesis -
Cube or Group By columns with Case Expressions with a total row (SQL Server 2008)
I am trying to create a summary tabe of some data. I think that I can use Cube(my heart is not set on it though), but I cant figure a way to define new columns via a case expression and sum the new column. Lastly, I need to create a total row at the
bottom and I have no idea of how to do that except percent run the query and then run it again without the travel_city and union all the two tables
group by travaled_city, [COL1] =sum(expense) when dept = 1, [COL2]=sum(expense) when dept = 2, [COL3] = sum(expense) when group = 3, =[COL4]=sum(expense) when group = 1 and expense code = 0100,[COL5]= sum(expense) when group = 2 and expense code
= 0100, [COL6]sum(expense) when group = 3 and expense code = 0100, [COL7]=sum(expense) when (exp_paid)<30, [COL8] = sum(expense) when dept in ('4','5','6')
and have a grand total of each column
any help is greatly appreciatedWould this work?
select travaled_city,
sum(case dept when 1 then expense else 0 end) as [COL1],
sum(case dept when 2 then expense else 0 end) as [COL2], ... -
Case expression in where clause
I have requirement to select a columns based on condition Datacode should (when the column id=1 THEN 'GILL' ELSE WHEN ID=11 THEN IT Should be 'HEL'
how can i write in case statment
AND DATA_CD =CASE WHEN ID=1 THEN 'GIL'
WHEN ID=11 THEN 'HEL'
END ) my question is above code is corrrect for where clause?
what happens to the ELSE PART?
Please clarify
Soraclehema wrote:
I have requirement to select a columns based on condition Datacode should (when the column id=1 THEN 'GILL' ELSE WHEN ID=11 THEN IT Should be 'HEL'
how can i write in case statment
AND DATA_CD =CASE WHEN ID=1 THEN 'GIL'
WHEN ID=11 THEN 'HEL'
END ) my question is above code is corrrect for where clause?
what happens to the ELSE PART?It is for you to tell what happens to the ELSE part.
If the ID is not 1 or 11, then your AND condition fails and probably your query will not retrieve any records for you (Assuming this query is not a part of OR condition, because there is no query provided.).
Because, without ELSE, the default shall be set to NULL and since you used "DATA_CD =", NULL shall not equate with it resulting in failure of condition. Hence, I would suggest you to add some default value in the ELSE part. -
Hi Experts !
can you please help me out is removing bug from this statement
select
CASE when p.ASSIGNED is null then
+(+
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID=1 and trunc(P.INSERT_DATE)= trunc(Sysdate)
and p.INITIATED_BY = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
+) planToday,+
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID=1
and p.INITIATED_BY = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
+) planTotal+
+)+
ELSE
+(+
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID= 1 and trunc(P.INSERT_DATE)= trunc(Sysdate)
and p.ASSIGNED = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
+) planToday,+
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID=1
and p.ASSIGNED = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
+) planTotal+
+)+
END
from WF_PLAN P
when i run the query, it gives me
Error Ora - 00907 : 'Missing Right Parenthesis'
Please help out!
Edited by: Zia on Jun 1, 2010 12:55 AMWhat exactly are your expecting the below given segment to display? Two different columns? (That's not the way to get it done)
CASE when p.ASSIGNED is null then
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID=1 and trunc(P.INSERT_DATE)= trunc(Sysdate)
and p.INITIATED_BY = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
SUM (
CASE WHEN P.STATUS = 'waiting' AND P.TYPE_ID=1
and p.INITIATED_BY = 51 and p.IS_DELETE='No' THEN 1 ELSE 0 END
)also you cannot alias a column within case..end.
*009*
Edited by: 009 on Jun 1, 2010 12:17 AM -
Hierarchy on HANA Calculation View with Optional Input Parameters Fails
Hi,
Has anyone succeeded in building a hierarchy on top of a calculation view with optional input parameters, where an input parameter is not filled?
The original requirement came from the wish to create a parent child hierarchy on a calculation view that was copied into the customer space from a HANA Live Financial Statement query view, but I have found the following when creating a simple level hierarchy on a calculation view that consumes one table. The Calculation View has one Input Parameter where the 'mandatory' box is unchecked.
Calculation view reads ECC table FAGLFLEXT
Simple level based hierarchy on fields PRCTR, RACCT and SEGMENT
Input parameter is used as a filter for PRCTR with logic ("EMPTY" = '$$P_PROFITCTR$$' or "PRCTR" = '$$P_PROFITCTR$$')
When I run the view I see the following behaviour in HANA Studio and Analysis for Excel
Before building the hierarchy I could run the view with or without the Input Parameter
After building the hierarchy I can run the view with the Input Parameter filled, but it fails when the Input Parameter is not filled.
Error message is "error: search table error: [2426] missing placeholder; missing value for mandatory parameter P_PROFITCTR"
P_PROFITCTR is not a mandatory parameter, but the selection for the hierarchy view thinks it should be. I don't find any notes around this issue, so I don't think it's version related, however the version I have used for this test is 1.00.70.
It's a shame we can't currently build the hierarchy as the parent child relationship is provided in HANA Live view NewGLFinancialStatementQuery.
Thanks,
KenHi Ken,
We have been facing similar issue. We have even tried to set default value and as optional parameter. View still fails to create hierarchy (we are not using HANA live). As mentioned on page 97 of HANA modelling guide input parameter is mandatory from engine point of view. Hierarchy is generated as column view during the initial activation of calculation view and therefore expect a value by caller.
This seems to be a product error. Some one from HANA development team should explain this issue in detail. I would expect someone like Thomas Jung reply to us.
At the moment, we cant use input parameter for date prompt which gives us calendar popup feature for date selection. Hierarchies just don't work with input parameter. We are missing something.
Regards
Angad -
select count(*)
from vwsr_all_merged_data s
where sr_tio_priority in ('Level 0','CEO','TER','Priority Assistance','Enquiry')
and sr_status = 'Open'
and SR_BUS_UNIT IN ('Business Support and Improvement','Finance and Administration','Cust Sat Simplification and Productivity','Project New and Customer Experience','Corp Strategy and Customer Experience','Other')
COUNT(*)
126the same should be possible dynamically with Case expression ,before that i create the string as
SELECT
CASE
WHEN :name = 'BS&I' THEN ('('||''''||'Business Support and Improvement'||''''||','||''''||'Finance and Administration'||','||''''||'Cust Sat Simplification and Productivity'
||''''||','||''''||'Project New and Customer Experience'||''''||','||''''||'Corp Strategy and Customer Experience'||''''||','||''''||'Other'||''''||')')
ELSE null
END
FROM dual
CASEWHEN:NAME='BS&I'THEN('('||''''||'BUSINESSSUPPORTANDIMPROVEMENT'||''''||','||
('Business Support and Improvement','Finance and Administration,'Cust Sat Simplification and Productivity','Project New and Customer Experience','Corp Strategy and Customer Experience','Other')
SQL> var name varchar2(10)
SQL> exec :name:='BS&I'
PL/SQL procedure successfully completed.the same string query i put here within subquery to make above string , it does not work.
select count(*)--sr_bus_unit,count(trunc(sr_open_date))
from vwsr_all_merged_data s
where sr_tio_priority in ('Level 0','CEO','TER','Priority Assistance','Enquiry')
and sr_status = 'Open'
and SR_BUS_UNIT IN
( SELECT
CASE
WHEN :name = 'BS&I' THEN ('('||''''||'Business Support and Improvement'||''''||','||''''||'Finance and Administration'||','||''''||'Cust Sat Simplification and Productivity'
||''''||','||''''||'Project New and Customer Experience'||''''||','||''''||'Corp Strategy and Customer Experience'||''''||','||''''||'Other'||''''||')')
ELSE null
END
FROM dual
COUNT(*)--SR_BUS_UNIT,COUNT(TRUNC(SR_OPEN_DATE))
0Edited by: user13653962 on 24/01/2013 17:09
Edited by: user13653962 on 24/01/2013 17:10No man , it is still no working , anyhow i really appreciate yours help , yours help drive me to find other way and you contributed 70% to achieve the result. Next query worked.
SQL> SET DEFINE OFF;
SQL>
SQL> SELECT COUNT (*)
2 FROM vwsr_all_merged_data s
3 WHERE sr_tio_priority IN
4 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
5 AND sr_status = 'Open'
6 AND SR_BUS_UNIT IN
7 ('Business Support and Improvement',
8 'Finance and Administration',
9 'Cust Sat Simplification and Productivity',
10 'Project New and Customer Experience',
11 'Corp Strategy and Customer Experience',
12 'Other')
13 UNION ALL
14 SELECT COUNT (*) --sr_bus_unit,count(trunc(sr_open_date))
15 FROM vwsr_all_merged_data s
16 WHERE sr_tio_priority IN
17 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
18 AND sr_status = 'Open'
19 AND SR_BUS_UNIT IN
20 (SELECT CASE
21 WHEN 'BS&I' = 'BS&I'
22 THEN
23 ( ''''
24 || 'Business Support and Improvement'
25 || ''''
26 || ','
27 || ''''
28 || 'Finance and Administration'
29 || ''''
30 || ','
31 || ''''
32 || 'Cust Sat Simplification and Productivity'
33 || ''''
34 || ','
35 || ''''
36 || 'Project New and Customer Experience'
37 || ''''
38 || ','
39 || ''''
40 || 'Corp Strategy and Customer Experience'
41 || ''''
42 || ','
43 || ''''
44 || 'Other'
45 || '''')
46 ELSE
47 NULL
48 END
49 FROM DUAL)
50
SQL>
SQL>
SQL> /
COUNT(*)
126
0Second Query
SQL> var name varchar2(10)
SQL> exec :name:='BS&I'
PL/SQL procedure successfully completed.
SQL> set define off
SQL> SELECT COUNT (*) --sr_bus_unit,count(trunc(sr_open_date))
2 FROM vwsr_all_merged_data s
3 WHERE sr_tio_priority IN
4 ('Level 0', 'CEO', 'TER', 'Priority Assistance', 'Enquiry')
5 AND sr_status = 'Open'
6 AND SR_BUS_UNIT IN
7 (SELECT CASE
8 WHEN :NAME = 'BS&I'
9 THEN
10 ('Business Support and Improvement')
11 ELSE
12 NULL
13 END
14 FROM DUAL
15 UNION
16 SELECT CASE
17 WHEN :NAME = 'BS&I'
18 THEN
19 ('Finance and Administration')
20 ELSE
21 NULL
22 END
23 FROM DUAL
24 UNION
25 SELECT CASE
26 WHEN :NAME = 'BS&I'
27 THEN
28 ('Cust Sat Simplification and Productivity')
29 ELSE
30 NULL
31 END
32 FROM DUAL
33 UNION
34 SELECT CASE
35 WHEN :NAME = 'BS&I'
36 THEN
37 ('Project New and Customer Experience')
38 ELSE
39 NULL
40 END
41 FROM DUAL
42 UNION
43 SELECT CASE
44 WHEN :NAME = 'BS&I'
45 THEN
46 ('Corp Strategy and Customer Experience')
47 ELSE
48 NULL
49 END
50 FROM DUAL
51 UNION
52 SELECT CASE
53 WHEN :NAME = 'BS&I'
54 THEN
55 ('Other')
56 ELSE
57 NULL
58 END
59 FROM DUAL
60 )
61 /
COUNT(*)--SR_BUS_UNIT,COUNT(TRUNC(SR_OPEN_DATE))
126
SQL> -
hi all,
which is better to use in below two query's.
select empno from emp where deptno=10
union all
select empno from emp where deprno=20
or
select
case when deptno=10 then empno end case ,
case when deptno=20 then empno end case
from
emp
which is better?
will case expression in select statement will effect the performance?
regards
shashank .kHi,
shashank .kura wrote:
hi thanks for reply ,
now consider these two Please try the queries yourself before posting them. Ask specific questions, such as "Why does the first query produce ...?" or "I though the second query would produce ... using the standard scott.emp table. Why doesn't it?"
select empno,null from emp where deptno=10
union all
select null,empno from emp where deptno=20The query above will only produce results for rows where deptno=10 or 20 (a total of 8 rows in the standard scott.emp table).
and
select case when deptno=10 then empno else null end case ,
case when deptno=20 then empno else null end case from emp order by 1,2This second query will produce one output row for every row in the table (14 rows in the standatd scott.emp table. 8 of those rows will be the same as returned by the first query, and the other 6 will have NULL in both columns.) Also, both columns have the same alias, CASE. (The keyword to end a CASE expression is just END. If you say END CASE, then CASE is taken to be a column alais.)
The following gets the same results as your first query:
select case
when deptno=10 then empno
else null
end AS empno_10
, case
when deptno=20 then empno
else null
end AS empno_20
from emp
WHERE deptno IN (10, 20)
;This will be more efficient than a UNION, because it only has to make one pass through the table.
Edited by: Frank Kulash on Aug 19, 2011 10:26 AM -
Detail view with bind variable. TreeTable not showing all detail result.
I’m having trouble with treeTable using detail view with bind variables and where clause defined in VO definition.
Both, master and detail view objects, base on the same entity and have the same condition in where clause. The view objects also have bind variables, which are set in prepareRowSetForQuery() method.
Again, these are two different views, that get different result, based on value of one of the bind variable.
When I show results in two different tables on jsf page, where master table has "RowSelection" set on "single", all results are displayed in detail table.
But when I use treeTable, only the first result of the detail is shown.I tested it in applicationModule and it works, but i think that's the same as two tables on a jsf page.
This is the order in which overridden methods are called in ADF BC or two tables on jsf page
when clicking on row in master table.
PrepareRowSetForQueryDetail
executeQueryForCollection_Detail user param: 2
Object 2: class [Ljava.lang.Object; -> print of the object2[] parameter in executeQueryForCollection
List 0: Bind_ChildId -> viewLink parameter
List 1: 400035313 -> viewLink parameter value
getEstimatedRowCount_Detail
count: 2
getEstimatedRowCount_Detail
count: 2 And when i click on "expand node" in tree table:
getEstimatedRowCount_Root
count: 2
PrepareRowSetForQuery_Detail
executeQueryForCollection_Detail user param: 2
Object 2: class [Ljava.lang.Object;
List 0: Bind_ChildId -> viewLink parameter
List 1: 400035321
PrepareRowSetForQueryDetail
executeQueryForCollection_Detail user param: 2
Object 2: class [Ljava.lang.Object;
List 0: Bind_ChildId -> viewLink parameter
List 1: 400035313
getEstimatedRowCount_Root
count: 2
getEstimatedRowCount_Root
count: 2
getEstimatedRowCount_Root
count: 2
PrepareRowSetForQueryDetail
executeQueryForCollection_Detail user param: 2
Object 2: class [Ljava.lang.Object;
List 0: Bind_ChildId -> viewLink parameter
List 1: 400035313
PrepareRowSetForQueryDetail
executeQueryForCollection_Detail user param: 2
Object 2: class [Ljava.lang.Object;
List 0: Bind_ChildId -> viewLink parameter
List 1: 400035321
getEstimatedRowCount_Root
count: 2
getEstimatedRowCount_Root
count: 2Values of user parameters are OK. Is there another method that i should override?
I also noticed, that if detail view doesn't have user bind variables, the tree works fine and is shown even in ADF BC (aplication module).
I guess we loose a tree, when using bind variables in detail view object.
Is there a way around it? -
CASE/DECODE in WHERE caluse
Hi friends,
Let's consider an EMP table has the following structure and data:
create table EMP
EMPNO NUMBER(4) not null,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7,2),
COMM NUMBER(7,2),
DEPTNO NUMBER(2),
CONFDATE DATE
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7369, 'SMITH', 'CLERK', 7902, to_date('17-12-1980', 'dd-mm-yyyy'), 800, null, 20, to_date('27-12-1980', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7499, 'ALLEN', 'SALESMAN', 7698, to_date('20-02-1981', 'dd-mm-yyyy'), 1600, 300, 30, to_date('28-02-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7521, 'WARD', 'SALESMAN', 7698, to_date('22-02-1981', 'dd-mm-yyyy'), 1250, 500, 30, to_date('28-02-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7566, 'JONES', 'MANAGER', 7839, to_date('02-04-1981', 'dd-mm-yyyy'), 2975, null, 20, to_date('12-04-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7654, 'MARTIN', 'SALESMAN', 7698, null, 1250, 1400, 30, to_date('28-09-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7698, 'BLAKE', 'MANAGER', 7839, to_date('01-05-1981', 'dd-mm-yyyy'), 2850, null, 30, to_date('11-05-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7782, 'CLARK', 'MANAGER', 7839, to_date('09-06-1981', 'dd-mm-yyyy'), 2450, null, 10, to_date('19-06-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7788, 'SCOTT', 'ANALYST', 7566, null, 3000, null, 20, to_date('09-12-1982', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7839, 'KING', 'PRESIDENT', null, to_date('17-11-1981', 'dd-mm-yyyy'), 5000, null, 10, to_date('27-11-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7844, 'TURNER', 'SALESMAN', 7698, to_date('08-09-1981', 'dd-mm-yyyy'), 1500, 0, 30, to_date('18-09-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7876, 'ADAMS', 'CLERK', 7788, null, 1100, null, 20, to_date('12-01-1983', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7900, 'JAMES', 'CLERK', 7698, null, 950, null, 30, to_date('03-12-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7902, 'FORD', 'ANALYST', 7566, to_date('03-12-1981', 'dd-mm-yyyy'), 3000, null, 20, to_date('13-12-1981', 'dd-mm-yyyy'));
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, CONFDATE)
values (7934, 'MILLER', 'CLERK', 7782, to_date('23-03-1981', 'dd-mm-yyyy'), 1300, null, 10, to_date('31-05-1981', 'dd-mm-yyyy'));
commit;
Now I need to fetch the employees whose hire date is between 01-APR-1981 and 31-DEC-1981. If the hire date is null, then confirmation date has to be considered.
For this input the following employees's records should be returned:
7566
7654
7698
7782
7839
7844
7900
7902
I tried with CASE, DECODE in WHERE clause. But I couldn't succeed. Please help.
Thanks in advance.
IniyavanSQL> ed
Wrote file afiedt.buf
1* select * from emp_test where nvl(hiredate,confdate) between '01-APR-1981' and '31-DEC-1981'
SQL> /
EMP_TESTNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CONFDATE
7566 JONES MANAGER 7839 02-APR-81 2975 20 12-APR-81
7654 MARTIN SALESMAN 7698 1250 1400 30 28-SEP-81
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 11-MAY-81
7782 CLARK MANAGER 7839 09-JUN-81 2450 10 19-JUN-81
7839 KING PRESIDENT 17-NOV-81 5000 10 27-NOV-81
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 18-SEP-81
7900 JAMES CLERK 7698 950 30 03-DEC-81
7902 FORD ANALYST 7566 03-DEC-81 3000 20 13-DEC-81
8 rows selected.@boopathi: Why to_char is needed here ? Further to_char(hire date,'DD_MON_YY') and comparing with '01-APR-1981' ? and WHAT is "_" doing in date format ? You sholud test your query before posting.
Edited by: Saubhik on May 17, 2010 11:33 PM -
Using CASE in the join statement in the AND clause. Where's the problem?
All,
I have my code, where based on the case statement, I would like to restrict the number of records in my JOIN condition. It's the CASE statement that I have used, that's giving me the problem. Not sure, what the problem is. The error says (in my case expression):
Msg 102, Level 15, State 1, Line 59
Incorrect syntax near '>'.
Select a.Col1, a.Col2, b.Col1, b.Col2, b.Col3
From Table1 a
Join Table2 b
On a.id = b.id
Join Table3 c
On c.FiltId = a.FiltId
And
Case
When b.Col3 <> 5 --b.Col3 is an INT field
Then (b.OutDate >= DATEADD(DAY, -30, c.InsertDate) And b.OutDate <= DATEADD(DAY, 30, c.InsertDate))
When b.Col3 = 5
Then (b.InDate >= DATEADD(DAY, 5, c.InsertDate))
End
Join Table 4 -- Other Join conditions and where clause conditionsYou do not know the CASE is an expression and fields are not columns. This is fundamental and probably means that a lot of your code needs work.
You can probably re-write the query with something like this:
SELECT A.col1, A.col2, B.col1, B.col2, B.col3
FROM Table_1 AS A, Table_2 AS B, Table_3 AS C
WHERE A.generic_id = B.generic_id
AND C.foobar_id = A.foobar_id
AND CASE
WHEN B.col3 <> 5
AND (B.something_out_date
<= DATEADD(DAY, -30, C.something_insertion_date)
THEN 'T'
WHEN B.col3 = 5
AND (B.something_out_date
>= DATEADD(DAY, -30, C.something_insertion_date)
THEN 'T'
ELSE 'F' END = 'T' ;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
11g outer join with case statement - strange results.
Hello All,
I am experiencing a strange issues in 11g while using case statement.
I am not able to reproduce this using sample data. Not sure what is wrong.
I am not narrowing it to say the usage of case statemnt is giving wrong results, but that is my observation when I am doing trail and error testing.
Here are the details.
My Version
SQL> select * from v$version;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
PL/SQL Release 11.2.0.2.0 - Production
CORE 11.2.0.2.0 Production
TNS for Linux: Version 11.2.0.2.0 - Production
NLSRTL Version 11.2.0.2.0 - Production
SQL> My Query
SELECT *
FROM (SELECT DISTINCT mf.schedule,
mf.cptcode,
NVL (mf.modifier, '00') modifier2,
CASE
WHEN mf.feetype = 'H'
AND mf.multiplier IS NOT NULL THEN
' 0.00'
WHEN (mf.feetype != 'H'
OR mf.feetype IS NULL)
AND mf.rbrvsvalue IS NOT NULL
AND mf.multiplier IS NOT NULL THEN
LPAD ( TRIM (TO_CHAR ( (mf.rbrvsvalue * mf.multiplier) / 100, 9999999.99)), 10)
ELSE
NULL
END
fee
FROM provider.mpifee mf, mpi_udffee.udffeeactivecptcodes vld
WHERE mf.schedule = 'SAPG1'
AND mf.cptcode = vld.cptcode
AND NVL (mf.modifier, 'NULL') = NVL (vld.modifier, 'NULL')) inline_fee,
(SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
FROM mpi_udffee.udffeeancfeedata arc
WHERE monthofextract = '201202'
AND arc.schedule = 'SAPG1'
AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate) inline_data
WHERE inline_fee.schedule = inline_data.col1(+)
AND inline_fee.cptcode = inline_data.col2(+)
AND inline_fee.modifier2 = inline_data.col3(+);
In the above query the inline view inline_data returns zero rows. but NVL is still getting applied for col3 and I am getting 00 in the results( strange ).
Results:
SCHEDULE CPTCO MODIFIER2 FEE COL1 COL2 COL3
SAPG1 49590 00 667.32 00
SAPG1 49611 00 781.03 00
SAPG1 49905 00 443.79 00
SAPG1 50205 00 883.56 00
SAPG1 50220 00 1315.15 00
SAPG1 50230 00 1638.74 00
SAPG1 50234 00 1666.16 00
SAPG1 50250 00 1566.14 00
SAPG1 50327 00 262.04 00
SAPG1 50541 00 1183.31 00
SAPG1 50620 00 1156.88 00
SAPG1 50650 00 1321.96 00
497 rows selected.
Just the inline view inline_data,
SQL> SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
2 FROM mpi_udffee.udffeeancfeedata arc
3 WHERE monthofextract = '201202'
4 AND arc.schedule = 'SAPG1'
5 AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate;
no rows selectedMuch unusual thing is when I just remove the case statement from the inline view "inline_fee", I am getting right results,
SELECT *
FROM (SELECT DISTINCT mf.schedule,
mf.cptcode,
NVL (mf.modifier, '00') modifier2 <-- Removed Case statement here
FROM provider.mpifee mf, mpi_udffee.udffeeactivecptcodes vld
WHERE mf.schedule = 'SAPG1'
AND mf.cptcode = vld.cptcode
AND NVL (mf.modifier, 'NULL') = NVL (vld.modifier, 'NULL')) inline_fee,
(SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
FROM mpi_udffee.udffeeancfeedata arc
WHERE monthofextract = '201202'
AND arc.schedule = 'SAPG1'
AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate) inline_data
WHERE inline_fee.schedule = inline_data.col1(+)
AND inline_fee.cptcode = inline_data.col2(+)
AND inline_fee.modifier2 = inline_data.col3(+);
SCHEDULE CPTCO MODIFIER2 COL1 COL2 COL3
SAPG1 46730 00
SAPG1 46735 00
SAPG1 46748 00
SAPG1 46760 00
SAPG1 46942 00
SAPG1 46945 00
SAPG1 47015 00
SAPG1 47125 00
SAPG1 47350 00
SAPG1 47505 00
SAPG1 47553 00interestingly explain plan for both the statements are exactly same,
SELECT STATEMENT ALL_ROWSCost: 138 Bytes: 1,078,274 Cardinality: 11,471
9 HASH JOIN RIGHT OUTER Cost: 138 Bytes: 1,078,274 Cardinality: 11,471
2 PARTITION RANGE EMPTY Cost: 2 Bytes: 150 Cardinality: 3
1 TABLE ACCESS FULL TABLE MPI_UDFFEE.UDFFEEANCFEEDATA Cost: 2 Bytes: 150 Cardinality: 3
8 VIEW MPI_UDFFEE. Cost: 135 Bytes: 504,724 Cardinality: 11,471
7 HASH UNIQUE Cost: 135 Bytes: 539,137 Cardinality: 11,471
6 HASH JOIN Cost: 134 Bytes: 539,137 Cardinality: 11,471
3 TABLE ACCESS FULL TABLE MPI_UDFFEE.UDFFEEACTIVECPTCODES Cost: 13 Bytes: 177,345 Cardinality: 25,335
5 PARTITION LIST SINGLE Cost: 120 Bytes: 600,600 Cardinality: 15,015 Partition #: 8
4 INDEX RANGE SCAN INDEX (UNIQUE) REPRICE.PK_MPIFEE Cost: 120 Bytes: 600,600 Cardinality: 15,015 Partition #: 9 Partitions accessed #11Is there anything wrong with the query? If not have anyone come across this issue or posted it as a bug or is there a patch?
Update:
when I set the parameter "_complex_view_merging"=false I am getting the right results even with case statement. But I don want to do some thing unsupported.
Are there any other viable solutions?
I appreciate the help.
Thanks,
G.
Edited by: Ganesh Srivatsav on Apr 10, 2012 12:37 PMHi Tubby,
Right, the query transformation is going wrong. Following is from trace,
SELECT "INLINE_FEE"."SCHEDULE" "SCHEDULE",
"INLINE_FEE"."CPTCODE" "CPTCODE",
"INLINE_FEE"."MODIFIER2" "MODIFIER2",
"INLINE_FEE"."FEE" "FEE",
"ARC"."SCHEDULE" "COL1",
"ARC"."PROCEDURECODE" "COL2",
CASE
WHEN "ARC".ROWID IS NOT NULL THEN NVL ("ARC"."MODIFIER", '00')
ELSE NULL
END
"COL3"
FROM (SELECT DISTINCT "MF"."SCHEDULE" "SCHEDULE",
"MF"."CPTCODE" "CPTCODE",
NVL ("MF"."MODIFIER", :B2) "MODIFIER2",
CASE
WHEN ("MF"."FEETYPE" = :B3
AND "MF"."MULTIPLIER" IS NOT NULL) THEN
:B4
WHEN ( ("MF"."FEETYPE" <> :B5
OR "MF"."FEETYPE" IS NULL)
AND "MF"."RBRVSVALUE" IS NOT NULL
AND "MF"."MULTIPLIER" IS NOT NULL) THEN
LPAD ( TRIM (TO_CHAR ( "MF"."RBRVSVALUE" * "MF"."MULTIPLIER" / :B6, :B7)), :B8)
ELSE
NULL
END
"FEE"
FROM "PROVIDER"."MPIFEE" "MF", "MPI_UDFFEE"."UDFFEEACTIVECPTCODES" "VLD"
WHERE "MF"."SCHEDULE" = 'SAPG1'
AND "MF"."CPTCODE" = "VLD"."CPTCODE"
AND NVL ("MF"."MODIFIER", 'NULL') = NVL ("VLD"."MODIFIER", 'NULL')) "INLINE_FEE",
"MPI_UDFFEE"."UDFFEEANCFEEDATA" "ARC"
WHERE "INLINE_FEE"."SCHEDULE" = "ARC"."SCHEDULE"(+)
AND "INLINE_FEE"."CPTCODE" = "ARC"."PROCEDURECODE"(+)
AND "INLINE_FEE"."MODIFIER2" = CASE
WHEN ("ARC".ROWID(+) IS NOT NULL) THEN NVL ("ARC"."MODIFIER"(+), '00')
ELSE NULL
END
AND "ARC"."MONTHOFEXTRACT"(+) = '201202'
AND "ARC"."SCHEDULE"(+) = 'SAPG1'
AND TRUNC (SYSDATE-10) >= "ARC"."RECORDEFFECTIVEDATE"(+)
AND TRUNC (SYSDATE-10) <= "ARC"."RECORDTERMINATIONDATE"(+)Does this refer to a specific bug?
Thanks,
G. -
Writing single query with conflicting WHERE statements
How do I run the following as a single query that will result in a column that pertains to the first block of code and then another column that pertains to the 2nd block of code? The issue is that I need 2 different WHERE statements. So the final output will be patient_id, complete, incomplete.
SELECT patient_id, COUNT(*) AS complete
FROM STATUS
WHERE status = 1
GROUP BY patient_id
ORDER BY patient_id;
SELECT patient_id, COUNT(*) AS incomplete
FROM STATUS
WHERE status = 2
GROUP BY patient_id
ORDER BY patient_id;
Thanks!Hi,
apex wrote:
Thanks for all of the help.
I would like to add another column with decile and am struggling as to how to do it. Since I can't reference something in a calculation in the same step, I think I will need a 3rd nesting, but what I haven't figured out is how to get the number of subjects whose ratio is less than that subject's ratio. Right: you can't assign an alias (such as complete or ratio) to a calculated column and use that alias in the same sub-query.
If the calculation isn't very complicated, then you might find it simpler just to repeat the calculation. For example, I think this is what you want:
WITH got_complete AS
SELECT patient_id
, COUNT ( CASE WHEN status = 1 THEN 1 END ) AS complete
, COUNT ( CASE WHEN status = 2 THEN 1 END ) AS incomplete
FROM pt_status
WHERE status IN (1,2)
GROUP BY patient_id
SELECT patient_id, complete, incomplete
, complete / (complete + incomplete) AS Ratio
, RANK () OVER ( ORDER BY complete / (complete + incomplete) ) - 1
AS decile
FROM got_complete
ORDER BY complete
, incomplete DESC
;RANK numbers rows 1, 2, 3, ... If I understand your requirements, you want the numbering to start with 0 (meaning "there are 0 other patients with a lower ratio"), so that's why I subtracted 1.
Depending how you want to handle ties, you may need to add some tie-breaker expressions to the analytic ORDER BY clause, and/or use ROW_NUMBER instead of RANK.
Here, I used the calculation "complete / (complete + incomplete)" in the ratio column, then repeated it in the decile column.
I you want, you can add another sub-query, called got_ratio, which would add the ratio column, but do nothing about the decile column. Then, in the main query, you could use RANK as shown above (or, as you suggested, a scalar sub-query referencing got_ratio) to get the number of other pateient_ids with lower ratios.
On the other hand, you could do this whole job without any sub-queries, using AVG as I did earlier, and then repeating that same AVG expression in the ORDER BY clause for RANK. Aggregate functions are computed before analytic fucntions, so the analytic RANK can referenece the aggregate AVG.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data. Include examples of decile ties (2 or more patients with the same ratio).
Explain, using specific examples, how you get those results from that data. -
Update with case statement problem.
Hi,
I have this statement
update tab_tr set col_rate =
case
when col_ern_type in ('031','035','036') then (1.5 * col_rate)
when col_ern_type in ('041','045','046') then (2 * col_rate)
end;this statement updated some 2 million rows in the table tab_tr. But the total count of rows for col_ern_type in ('031','035','036', '041','045','046') yeild only around 222642 rows.
select count(*) from tab_tr where col_ern_type in ('031','035','036', '041','045','046'); --> 222642 rowswhat is the problem with the above update statement.
Thank you,Hi,
DBA_1976 wrote:
... I thought the case statement conditions are counted as the where condition. But ......A CASE expression just takes the place of some other expression, such as a literal, a function, or a column.
For example, which rows do you think this should update?
UPDATE tab_tr
SET col_rate = 100;It would update all rows, of course.
How about this statement?
UPDATE tab_tr
SET col_rate = column_x;Will it only change the rows where column_x are a certain value, or not NULL, or in any way depend on column_x? No, of course not. It will update all rows.
How about this statement?
UPDATE tab_tr
SET col_rate = function_y (col_ern_type);Will it only change the rows where the fucntion returns a certain value? Will it depend on the value in col_ern_type? No, of course not. It calls the function for each row, and whatever the function returns (even if the function returns NULL), that's what goes into col_rate on each row.
A CASE expression is just something that you can substitute in place of any other expression, such as the literal 100, or the column column_x, or the function function_y in the statements above. Naturally, the value that gets put into col_rate will depend on what the CASE expression returns, but the behavior of the UPDATE statement as a whole will not.
Maybe you are looking for
-
While saving the delivery no in VA02 dump error showing (Arithmatic overflo
Hi, while saving the delivery no in VA02, one dump error getting displayed. Arithmatic over flow occurs. Can any one can say how to rectify the program to avoid dump error The below lines are showing in dump. Waiting for quick response. Error analysi
-
Unable to create BI JDBC connection in JDeveloper
I'm trying to follow the steps in http://docs.oracle.com/cd/E28271_01/bi.1111/e10545/sql_bi_view_object.htm#BHAFJIHC to create JDBC connection. But when I click on Test, it shows Working.. and never returns with success or failure messages. username:
-
I want to post service tax gl (liability) in KZ document type
Dear all, I want to post service tax gl (liability) in KZ document type .in my customization document aplitting is active.it has not allow to post liability gl against bank.I want to post entry Vendor dr
-
Adobe Encore CS4 crashes during Render Progress
After creating entire menu without any problems ( there is occasional encore system crash...) I go to File and then Render Project. Rendering process start with rendering of my audio file and then it goes to "Rendering menu" and crashes every time! I
-
Just i notice a heap memory notification in alert.log file
Hi, i notice that whenever a user exectuing a qurey this heap memory notification is coming in alert.log file. Memory Notification: Library Cache Object loaded into SGA Heap size 2294K exceeds notification threshold (2048K). what it is actully tell m