Case Statement and Sequential Count
I would like to obtain user input via a prompt and use what the user selects in my OBIEE Report case statement. I ve done the parameter part with a presentation variable.
and a filter with the following.
Recv Date is between @{Repair_Start_Date}{01-01-2013} and @{Repair_End_Date}{01-01-2013}
Now I would like to have a sequential count of the records that meet the case statement, please advise.
For example &START_DATE AND &END_DATE are user inputs:
CASE when SHIP_DATE BETWEEN &START_DATE AND &END_DATE THEN 1
Thanks
Hi,
Here is a way you could try.
CASE when SHIP_DATE BETWEEN &START_DATE AND &END_DATE THEN RSUM(1) END
So, what it does?
Whenever the CASE statement is satisfied, it increments 1 by 1.
Hope this helps.
Thank you,
Dhar
Similar Messages
-
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
제품 : PL/SQL
작성날짜 : 2001-11-13
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
=======================================================
PURPOSE
아래의 자료는 Case 문에서 oracle 8.1.7과 Oracle 9i의 New Feature로 8.1.7에서는
sqlplus 에서만 가능했고, 9i 부터는 pl/sql 까지 가능하다.
Explanation
1. Oracle 8.1.7 Feature
Oracle 8.1.7 에서 Case 문은 Decode 문과 유사하지만, 기존의 decode 문을 쓰는 것보다
더 많은 확장성과 Logical Power와 좋은 성능을 제공한다. 주로 나이와 같이 category 별로
나눌때 주로 사용하고 Syntex는 아래와 같다.
CASE WHEN <cond1> THEN <v1> WHEN <cond2> THEN <v2> ... [ELSE <vn+1> ] END
각각의 WHEN...THEN 절의 argument 는 255 까지 가능하고 이 Limit를 해결하려면
Oracle 8i Reference를 참조하면 된다.
The maximum number of arguments in a CASE expression is 255, and each
WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices,
you can nest CASE expressions. That is expr1 can itself be a CASE expression.
Case Example : 한 회사의 모든 종업원의 평균 봉급을 계산하는데 봉급이 $2000보다 작은경우
2000으로 계산을 하는 방법이 pl/sql을 대신하여 case function을 사용할 수 있다.
SELECT AVG(CASE when e.sal > 2000 THEN e.sal ELSE 2000 end) FROM emp e;
Case Example : 나이를 column으로 가지고 있는 customer table을 예로 들어보자.
SQL> SELECT
2 SUM(CASE WHEN age BETWEEN 70 AND 79 THEN 1 ELSE 0 END) as "70-79",
3 SUM(CASE WHEN age BETWEEN 80 AND 89 THEN 1 ELSE 0 END) as "80-89",
4 SUM(CASE WHEN age BETWEEN 90 AND 99 THEN 1 ELSE 0 END) as "90-99",
5 SUM(CASE WHEN age > 99 THEN 1 ELSE 0 END) as "100+"
6 FROM customer;
70-79 80-89 90-99 100+
4 2 3 1
1 SELECT
2 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
3 WHEN age BETWEEN 80 and 89 THEN '80-89'
4 WHEN age BETWEEN 90 and 99 THEN '90-99'
5 WHEN age > 99 THEN '100+' END) as age_group,
6 COUNT(*) as age_count
7 FROM customer
8 GROUP BY
9 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
10 WHEN age BETWEEN 80 and 89 THEN '80-89'
11 WHEN age BETWEEN 90 and 99 THEN '90-99'
12* WHEN age > 99 THEN '100+' END)
SQL> /
AGE_G AGE_COUNT
100+ 1
70-79 4
80-89 2
90-99 3
Example
2. Oracle 9i Feature
Oracle 9i부터는 pl/sql에서도 case문을 사용할 수 있으면 이것은
복잡한 if-else 구문을 없애고, C언어의 switch문과 같은 기능을 한다.
아래의 9i pl/sql Sample 및 제약 사항을 보면 아래와 같다.
Sample 1:
A simple example demonstrating the proper syntax for a case
statement
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case achar
when 'A' then dbms_output.put_line('The description was Excellent');
when 'B' then dbms_output.put_line('The description was Very Good');
when 'C' then dbms_output.put_line('The description was Good');
when 'D' then dbms_output.put_line('The description was Fair');
when 'F' then dbms_output.put_line('The description was Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 2:
A simple example demonstrating the proper syntax for a case
expression
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case achar
when 'A' then 'Excellent'
when 'B' then 'Very Good'
when 'C' then 'Good'
when 'D' then 'Fair'
when 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
NOTE: The above simple samples demonstrate two subtle differences in the
syntax
required for case statements and expressions.
1) A case STATEMENT is terminated using the 'end case' keywords; a
case
EXPRESSION is terminated using only the 'end' keyword.
2) Each item in a case STATEMENT consists of one or more
statements, each
terminated by a semicolon. Each item in a case expression
consists of
exactly one expression, not terminated by a semicolon.
Sample 3:
Sample 1 demonstrates a simple case statement in which the selector
is
compared for equality with each item in the case statement body.
PL/SQL
also provides a 'searched' case statement as an alternative; rather
than
providing a selector and a list of values, each item in the body of
the
case statement provides its own predicate. This predicate can be any
valid boolean expression, but only one case will be selected.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case
when achar = 'A' then dbms_output.put_line('The description was
Excellent');
when achar = 'B' then dbms_output.put_line('The description was Very
Good');
when achar = 'C' then dbms_output.put_line('The description was
Good');
when achar = 'D' then dbms_output.put_line('The description was
Fair');
when achar = 'F' then dbms_output.put_line('The description was
Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 4:
This sample demonstrates the proper syntax for a case expression of
the
type discussed in Sample 3 above.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case
when achar = 'A' then 'Excellent'
when achar = 'B' then 'Very Good'
when achar = 'C' then 'Good'
when achar = 'D' then 'Fair'
when achar = 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 5:
This sample demonstrates the use of nested case statements. It is
also
permissable to nest case expressions within a case statement (though
it
is not demonstrated here), but nesting of case statements within a
case
expression is not possible since statements do not return any value.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
case anum1
when 1 then case anum2
when 1 then answer := 10;
when 2 then answer := 20;
when 3 then answer := 30;
else answer := 999;
end case;
when 2 then case anum2
when 1 then answer := 15;
when 2 then answer := 25;
when 3 then answer := 35;
else answer := 777;
end case;
else answer := 555;
end case;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 6:
This sample demonstrates nesting of case expressions within another
case
expression. Note again the absence of semicolons to terminate both
the
nested case expression and the individual cases of those
expressions.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
answer :=
case anum1
when 1 then case anum2
when 1 then 10
when 2 then 20
when 3 then 30
else 999
end
when 2 then case anum2
when 1 then 15
when 2 then 25
when 3 then 35
else 777
end
else 555
end;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Although PL/SQL anonymous blocks have been used in all of the examples
so far,
case statements and expressions can also be used in procedures,
functions, and
packages with no changes to the syntax.
The following samples are included for completeness and demonstrate the
use of
case statements and/or expressions in each of these scenarios.
Sample 7:
This sample demonstrates use of a case statement in a stored
procedure.
Note that this sample also demonstrates that it is possible for each
of
the items in the case body to consist of more than one statement.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
exec testcasestmt(&anum);
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 8:
This sample demonstrates the use of a case statement in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg2 is
procedure testcasestmt ( anum IN number );
function testcasestmt_f ( anum IN number ) return number;
end testpkg2;
create or replace package body testpkg2 is
procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
function testcasestmt_f ( anum IN number ) return number is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
return anum;
end;
end testpkg2;
exec testpkg2.testcasestmt(&anum);
variable numout number
exec :numout := testpkg2.testcasestmt_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 9:
This sample demonstrates the use of a case expression in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg is
procedure testcase ( anum IN number );
function testcase_f ( anum IN number ) return number;
end testpkg;
create or replace package body testpkg is
procedure testcase ( anum IN number ) is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
end;
function testcase_f ( anum IN number ) return number is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
return anothernum;
end;
end testpkg;
variable numout number
exec testpkg.testcase(&anum);
exec :numout := testpkg.testcase_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
제약 사항
다음의 databasetype은 case 문에서 지원되지 않는다.
BLOB
BFILE
VARRAY
Nested Table
PL/SQL Record
PL/SQL Version 2 tables (index by tables)
Object type (user-defined type)
All of these types except for object types face a similar restriction
even for if statements (i.e. they cannot be compared for equality directly) so this is unlikely to change for these types. Lack of support for object types is simply an implementation restriction which may be relaxed in future releases.
Reference Ducumment
Oracle 8.1.7 Manual
NOTE:131557.1I have done the following code but doesn't
like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
I'm guessing it won't compile because you're trying to switch on a Button.
I tried something
like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
Would appreciate it if someone could tell me how to position
shapes using the graohic method. I think the problem is that you're confusing shapes with components. -
Case statement and Decode function both are not working in Select cursor.
I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. On the other hand both the things work in just select statement.
See the first column in select (PAR_FLAG), I need to have this evaluated along with other fields. Can you please suggest some thing to make this work. And also I would like to
know the reason why decode is not working, I heard some where Case statement do not work with 8i.
Author : Amit Juneja
Date : 06/20/2011
Description:
Updates the Diamond MEMBER_MASTER table with the values from
INC.MEM_NJ_HN_MEMBER_XREF table.
declare
rec_cnt number(12) := 0;
commit_cnt number(4) := 0;
cursor select_cur is
Select DECODE(1,
(Select 1
from hsd_prov_contract R
where R.seq_prov_id = PM.seq_prov_id
and R.line_of_business = H.line_of_business
and R.PCP_FLAG = 'Y'
and R.participation_flag = 'P'
and SYSDATE between R.EFFECTIVE_DATE AND
NVL(R.TERM_DATE,
TO_DATE('31-DEC-9999', 'DD-MON-YYYY'))),
'Y',
'N') PAR_FLAG,
H.SEQ_ELIG_HIST,
H.SEQ_MEMB_ID,
H.SEQ_SUBS_ID,
H.SUBSCRIBER_ID,
H.PERSON_NUMBER,
H.EFFECTIVE_DATE,
H.TERM_DATE,
H.TERM_REASON,
H.RELATIONSHIP_CODE,
H.SEQ_GROUP_ID,
H.PLAN_CODE,
H.LINE_OF_BUSINESS,
H.RIDER_CODE_1,
H.RIDER_CODE_2,
H.RIDER_CODE_3,
H.RIDER_CODE_4,
H.RIDER_CODE_5,
H.RIDER_CODE_6,
H.RIDER_CODE_7,
H.RIDER_CODE_8,
H.MEDICARE_STATUS_FLG,
H.OTHER_STATUS_FLAG,
H.HIRE_DATE,
H.ELIG_STATUS,
H.PREM_OVERRIDE_STEP,
H.PREM_OVERRIDE_AMT,
H.PREM_OVERRIDE_CODE,
H.SEQ_PROV_ID,
H.IPA_ID,
H.PANEL_ID,
H.SEQ_PROV_2_ID,
H.SECURITY_CODE,
H.INSERT_DATETIME,
H.INSERT_USER,
H.INSERT_PROCESS,
H.UPDATE_DATETIME,
H.UPDATE_USER,
H.UPDATE_PROCESS,
H.USER_DEFINED_1,
H.SALARY,
H.PEC_END_DATE,
H.REASON_CODE,
H.PEC_WAIVED,
H.BILL_EFFECTIVE_FROM_DATE,
H.BILLED_THRU_DATE,
H.PAID_THRU_DATE,
H.SUBSC_DEPT,
H.SUBSC_LOCATION,
H.USE_EFT_FLG,
H.BENEFIT_START_DATE,
H.SEQ_ENROLLMENT_RULE,
H.MCARE_RISK_ACCRETION_DATE,
H.MCARE_RISK_DELETION_DATE,
H.MCARE_RISK_REFUSED_DATE,
H.COMMENTS,
H.USER_DEFINED_2,
H.USER_DEFINED_3,
H.RATE_TYPE,
H.PCPAA_OCCURRED,
H.PRIVACY_ON,
H.PCP_CHANGE_REASON,
H.SITE_CODE,
H.SEQ_SITE_ADDRESS_ID,
PM.seq_prov_id rendered_prov
from hsd_member_elig_history H,
INC.PCP_REASSIGN_RPRT_DATA P,
hsd_prov_master PM
where P.subscriber_id = H.subscriber_id
and P.rendered_pcp = PM.provider_ID
and H.elig_status = 'Y'
and (H.term_date is NULL or H.term_date >= last_day(sysdate))
order by H.Seq_memb_id;
begin
for C in select_cur loop
rec_cnt := rec_cnt + 1;
update hsd_member_elig_history
set term_date = TRUNC(SYSDATE - 1),
term_reason = 'PCPTR',
update_datetime = SYSDATE,
update_user = USER,
update_process = 'TD33615'
where seq_elig_hist = C.seq_elig_hist
and seq_memb_id = C.seq_memb_id;
INSERT INTO HSD_MEMBER_ELIG_HISTORY
(SEQ_ELIG_HIST,
SEQ_MEMB_ID,
SEQ_SUBS_ID,
SUBSCRIBER_ID,
PERSON_NUMBER,
EFFECTIVE_DATE,
TERM_DATE,
TERM_REASON,
RELATIONSHIP_CODE,
SEQ_GROUP_ID,
PLAN_CODE,
LINE_OF_BUSINESS,
RIDER_CODE_1,
RIDER_CODE_2,
RIDER_CODE_3,
RIDER_CODE_4,
RIDER_CODE_5,
RIDER_CODE_6,
RIDER_CODE_7,
RIDER_CODE_8,
MEDICARE_STATUS_FLG,
OTHER_STATUS_FLAG,
HIRE_DATE,
ELIG_STATUS,
PREM_OVERRIDE_STEP,
PREM_OVERRIDE_AMT,
PREM_OVERRIDE_CODE,
SEQ_PROV_ID,
IPA_ID,
PANEL_ID,
SEQ_PROV_2_ID,
SECURITY_CODE,
INSERT_DATETIME,
INSERT_USER,
INSERT_PROCESS,
UPDATE_DATETIME,
UPDATE_USER,
UPDATE_PROCESS,
USER_DEFINED_1,
SALARY,
PEC_END_DATE,
REASON_CODE,
PEC_WAIVED,
BILL_EFFECTIVE_FROM_DATE,
BILLED_THRU_DATE,
PAID_THRU_DATE,
SUBSC_DEPT,
SUBSC_LOCATION,
USE_EFT_FLG,
BENEFIT_START_DATE,
SEQ_ENROLLMENT_RULE,
MCARE_RISK_ACCRETION_DATE,
MCARE_RISK_DELETION_DATE,
MCARE_RISK_REFUSED_DATE,
COMMENTS,
USER_DEFINED_2,
USER_DEFINED_3,
RATE_TYPE,
PCPAA_OCCURRED,
PRIVACY_ON,
PCP_CHANGE_REASON,
SITE_CODE,
SEQ_SITE_ADDRESS_ID)
values
(hsd_seq_elig_hist.nextval,
C.SEQ_MEMB_ID,
C.SEQ_SUBS_ID,
C.SUBSCRIBER_ID,
C.PERSON_NUMBER,
trunc(SYSDATE),
C.TERM_DATE,
C.TERM_REASON,
C.RELATIONSHIP_CODE,
C.SEQ_GROUP_ID,
C.PLAN_CODE,
C.LINE_OF_BUSINESS,
C.RIDER_CODE_1,
C.RIDER_CODE_2,
C.RIDER_CODE_3,
C.RIDER_CODE_4,
C.RIDER_CODE_5,
C.RIDER_CODE_6,
C.RIDER_CODE_7,
C.RIDER_CODE_8,
C.MEDICARE_STATUS_FLG,
C.OTHER_STATUS_FLAG,
C.HIRE_DATE,
C.ELIG_STATUS,
C.PREM_OVERRIDE_STEP,
C.PREM_OVERRIDE_AMT,
C.PREM_OVERRIDE_CODE,
C.SEQ_PROV_ID,
C.IPA_ID,
C.PANEL_ID,
C.SEQ_PROV_2_ID,
C.SECURITY_CODE,
SYSDATE,
USER,
'TD33615',
SYSDATE,
USER,
'TD33615',
C.USER_DEFINED_1,
C.SALARY,
C.PEC_END_DATE,
C.REASON_CODE,
C.PEC_WAIVED,
C.BILL_EFFECTIVE_FROM_DATE,
C.BILLED_THRU_DATE,
C.PAID_THRU_DATE,
C.SUBSC_DEPT,
C.SUBSC_LOCATION,
C.USE_EFT_FLG,
C.BENEFIT_START_DATE,
C.SEQ_ENROLLMENT_RULE,
C.MCARE_RISK_ACCRETION_DATE,
C.MCARE_RISK_DELETION_DATE,
C.MCARE_RISK_REFUSED_DATE,
C.COMMENTS,
C.USER_DEFINED_2,
C.USER_DEFINED_3,
C.RATE_TYPE,
C.PCPAA_OCCURRED,
C.PRIVACY_ON,
C.PCP_CHANGE_REASON,
C.SITE_CODE,
C.SEQ_SITE_ADDRESS_ID);
commit_cnt := commit_cnt + 1;
if (commit_cnt = 1000) then
dbms_output.put_line('Committed updates for 1000 records.');
commit;
commit_cnt := 0;
end if;
end loop;
commit;
dbms_output.put_line('Total number of MEMBER_ELIG_HISTROY records inserted : ' ||
rec_cnt);
exception
when others then
raise_application_error(-20001,
'An error was encountered - ' || sqlcode ||
' -error- ' || sqlerrm);
end;user10305724 wrote:
I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. Please define what you mean by not working even if your computer screen is near the internet we can't see it.
You should also look at the FAQ about how to ask a question
SQL and PL/SQL FAQ
Particularly *9) Formatting with {noformat}{noformat} Tags* and posting your version.
know the reason why decode is not working, I heard some where Case statement do not work with 8i.
Does this mean you are using 8i? Then scalar sub queries - selects within the select list, are not supported, along with CASE in PL/SQL.
Select DECODE(1,
* (Select 1
from hsd_prov_contract R
where R.seq_prov_id = PM.seq_prov_id
and R.line_of_business = H.line_of_business
and R.PCP_FLAG = 'Y'
and R.participation_flag = 'P'
and SYSDATE between R.EFFECTIVE_DATE AND
NVL(R.TERM_DATE,
TO_DATE('31-DEC-9999', 'DD-MON-YYYY')))*,
'Y',
'N') PAR_FLAG,
>
exception
when others then
raise_application_error(-20001,
'An error was encountered - ' || sqlcode ||
' -error- ' || sqlerrm);
http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html -
Regarding case statement and decode function
Hi Experts,
I have question.....regarding case statement and decode statement....
Can you please explain me that which one will be efficient,to place in insert statement...
insert statement(
(case when ........then
case when ....then
else
end)
else
end)
or
insert statement(
case when.....then
decode(....)
else
end)
Can you people explain me which one is more efficient method?
Thanks in advance.......The are major differences to talk about in case of CASE vs DECODE, but performance wise both are pretty much the same.
Have a look at Tom's thread
Ask Tom &quot;better performance - case or decode&quot;
I would suggest to use CASE whenever possible. Don't worry about the performance part. -
Difference beween Case Statement and Pivot Operator in a OWB mapping
Hi ,
Kindly clarify what is the difference between using a PIVOT operator and the CASE statement in a Expression Operator in a particular mapping.
rgds
ArinjitHi
With PIVOT operator you can transform columns to rows. For example if oyu have 12 column (one for every months) than you can create 12 rows with one column of month data.
If you want to do this without PIVOT you can do it with union (12 times) or with
something like this.
In this case you can't use CASE statement I think.
If you want to do the reverse of this, create 12 column from 12 rows, you can use UNPIVOT operator. In this case you can use CASE statement and aggregating.
Ott Karesz
http://www.trendo-kft.hu -
Problem w/ Case Statement and Video Capture
Hey!
I've got a question about a topic which seems pretty trivial, but has been giving me quite the trouble for some time now. I was hoping that someone on this forum would be able to help me catch and fix my mistake.
Basically what I'm trying to do is capture video from a camera, run some video analysis for a certain duration, and store the raw footage for that same duration in an avi file. I'm using IMAQdx and a Logitech C920 camera to gather video. When I run the program, I want there to be an output of the raw video on the front panel. When I then hit a button, I would like the camera to save a .avi file of the video for a set number of frames and concurrently run some analysis and display the results on another display on the front panel. The purpose of the raw footage in the .avi file is to be able to run the analysis again at a later date.
I've attached both a screenshot and the .vi file to this post. When I run the current script, I'm confronted with one of two possible errors (not sure why they're different from time to time). The Video Acquisition Block either "Time Out"s or the Write to AVI block issues an incompatible image type error. The reason why I'm baffled by this is because when I take it out of the case statement and have it run with the rest of the program, the .avi file is generated accurately and stored.
Any help would be greatly appreciated. Thanks!
Attachments:
Script Image.png 39 KB
11_30_12 TrackVIEW.vi 271 KBGreetings,
Would the time out error happen every time you run the VI? In addition, do these errors have a code?
I was able to replicate the issue and initially believe that it might be that we are simultaneously opening two sessions to the same camera. Could you simply take a finite number of images from the first acquisition and chain the second one via sequence structure? It would limit the viewer to only view the video on the other Image Display during saving the AVI, but it might be worthwhile looking into.
It might also be worthwhile to consider enquewing a certain number of images whenever the button is pressed, but that would require some more programming logic.
Cordially;
Simon P.
National Instruments
Applications Engineer -
CASE Statement - and checking number ranges
I am attempting to write a bit of SQL that can be used to do a count of Requisition Values, in different value bands, e.g.:
0 - 250
251 - 500
501 - 1000
etc...
I have got this far:
SELECT sum_value
, COUNT(req_id) req_ct
FROM (SELECT prha.requisition_header_id req_id
, CASE SUM(prla.unit_price * prla.quantity)
WHEN 250
THEN '250'
WHEN 500
THEN '500'
WHEN 500
THEN '1000'
ELSE 'OTHER'
END sum_value
FROM po.po_requisition_headers_all prha
, po.po_requisition_lines_all prla
WHERE prha.requisition_header_id = prla.requisition_header_id
AND prha.creation_date >= SYSDATE - 3
GROUP BY prha.requisition_header_id
, prla.requisition_header_id) rt
GROUP BY sum_value;
SUM_V REQ_CT
250 3
500 6
OTHER 726But - it is not that great, in that it counts REQs with an exact value of 250,400,500 etc.
I am trying to work out the syntax to allow the CASE statement to work with ranges, but I can't work it out.
I have naively attempted this, for example:
WHEN > 250 AND 500
But that errors out, because I can see that the '>' needs to know what it is checking
Any help much appreciated.
Thank youThanks for the reply Sarma,
I've attempted that:
SELECT sum_value
, COUNT(req_id) req_ct
FROM (SELECT prha.requisition_header_id req_id
, CASE SUM(prla.unit_price * prla.quantity)
WHEN BETWEEN 250 AND 500
THEN '250 - 500'
WHEN BETWEEN 501 AND 1000
THEN '501 - 1000'
WHEN BETWEEN 1001 AND 2500
THEN '1001 - 2500'
ELSE 'OTHER'
END sum_value
FROM po.po_requisition_headers_all prha
, po.po_requisition_lines_all prla
WHERE prha.requisition_header_id = prla.requisition_header_id
AND prha.creation_date >= SYSDATE - 3
GROUP BY prha.requisition_header_id
, prla.requisition_header_id) rt
GROUP BY sum_value;But I can see that it doesn't work because I need to state what 'blah' is!
For example, if I tried to state 'blah' as follows:
SELECT sum_value
, COUNT(req_id) req_ct
FROM (SELECT prha.requisition_header_id req_id
, CASE SUM(prla.unit_price * prla.quantity)
WHEN SUM(prla.unit_price * prla.quantity) BETWEEN 250 AND 500
THEN '250 - 500'
WHEN SUM(prla.unit_price * prla.quantity) BETWEEN 501 AND 1000
THEN '501 - 1000'
WHEN SUM(prla.unit_price * prla.quantity) BETWEEN 1001 AND 2500
THEN '1001 - 2500'
ELSE 'OTHER'
END sum_value
FROM po.po_requisition_headers_all prha
, po.po_requisition_lines_all prla
WHERE prha.requisition_header_id = prla.requisition_header_id
AND prha.creation_date >= SYSDATE - 3
GROUP BY prha.requisition_header_id
, prla.requisition_header_id) rt
GROUP BY sum_value;It still errors. I guess I am doing something fundamentally wrong, but I can't see how I can refer to the 'sum' value, to then use it in the Between section of the Case statement.
Thanks -
How to manipulate arrays using case statements and boolean conditions?
In the vi that is attached I am trying to compare two values in two different arrays and delete the value that is equal to zero. The values of each array are rounded to the closest integer. Then I attempted to apply the ">0" boolean as the condition for my case statement, but I am getting an error. Any tips on manipulating arrays with case statements?
Attachments:
Patient Movement Monitoring.vi 141 KBThank you!!! that was a huge help. I don't think I need the case structures at all. The next part of the code compares the 4 values in the array.
If columns 0 and 1 are both positive -> output 1
If column 0 is negative and 1 is positive -> output 2
If columns 0 and 1 are both negative -> output 3
If column 0 is positive and 1 is negative -> output 4
(0 is x-axis value, 1 is y-axis value.....outputs are assigning quadrants to the combination)
Only one of the "AND" booleans will return true for each index. Is there a way to initialize another array of outputs 1-4 depending on which AND returns true?
Attachments:
Patient Movement Monitoring.vi 144 KB -
Case Statement and Group By issues
Hi this is my initial query which works perfectly:
select ff.cla_case_no, Cost_before_Decision, Cost_Of_Claim, decline, Decline_Description from
fraud_nov_14_final ff
,(select cla_case_no, (sum(total_cost_adj_old) + sum(decline_estimate)) Cost_before_Decision
from reporting.ci_final@test
group by cla_case_no) z
where ff.cla_case_no = z.cla_case_noI now want to add in a condition based on a column called decline:
select ff.cla_case_no, Cost_before_Decision, Cost_Of_Claim, ff.decline, Decline_Description from
fraud_nov_14_final ff
,(select cla_case_no, (case when decline = 1 or decline = 2 THEN (sum(total_cost_adj_old) + sum(decline_estimate)) ELSE Total_Cost END) Cost_before_Decision
from reporting.ci_final@test
group by cla_case_no) z
where ff.cla_case_no = z.cla_case_noThe error message I receive is :
ORA-00979: not a GROUP BY expression
00979. 00000 - "not a GROUP BY expression"
Thanks in advance for your help!!
Banner:
Oracle Database 11g 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 - ProductionYou would need DECLINE in the group by clause of your inner query.
Additionally you would need to change TOTAL_COST to SUM(TOTAL_COST) in where case statement.
But then you would retrieve one row for each value of DECLINE in this query.
You also could use this:
(I don't know if it will meet your requirements)
SELECT ff.cla_case_no,
cost_before_decision,
cost_of_claim,
ff.decline,
decline_description
FROM fraud_nov_14_final ff,
(SELECT cla_case_no,
SUM (decode(decline,1,total_cost_adj_old+decline_estimate,
2,total_cost_adj_old+decline_estimate,
total_cost)) cost_before_decision
FROM reporting.ci_final@test
GROUP BY cla_case_no) z
WHERE ff.cla_case_no = z.cla_case_no;(untested code, because I don't have your tables)
Edited by: hm on 23.11.2011 06:52 -
Hi,
When I try to group by a case statement , i get not "ORA-00979 not a group by emxpression"
select
CASE WHEN I.transaction_cd IN ('PAY0','PAY1') THEN
CASE When I.acct_cd In (Select 3201040 from dual) Then 'SP'
Else 'FYP'
End
END x
FROM Pol_daily I
group by
CASE WHEN I.txttransaction_cd IN ('PAY0','PAY1') THEN
CASE When I.txtacct_cd In (Select 3201040 from dual) Then 'SP'
Else 'FYP'
End
END
Can someone help me please.But result will be different..
SQL> select case when sal <1000 then '1' else '2' end c1, sum(sal) sl
2 from emp
3 group by case when sal <1000 then '1' else '2' end ;
C SL
1 1750
2 29275
SQL> ed
Wrote file afiedt.buf
1 select case when sal <1000 then '1' else '2' end c1, sum(sal) sl
2 from emp
3* group by sal
SQL> /
C SL
2 2450
2 5000
2 1300
2 2500
2 2850
2 2975
2 1100
2 2000
2 6000
1 800
2 1600
C SL
2 1500
1 950
13 rows selected. -
Basically what I am trying to do is create three Ovals (only mangaged to one but would appreciate some help if someone can tell me how to position ovals on a screen :=D) which when a single command is pressed the specified oval changes color, i.e. a traffic light system. I have done the following code but doesn't like the statement of - "case(butNext)". Can someone point me in the right direction :=). I tried something like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"... well something like that but was no good. Would appreciate it if someone could tell me how to position shapes using the graohic method. I know how to do it with command buttons, list boxes etc but its not the same with shapes :=(.
import java.awt.*;
import java.applet.*;
public class traffic extends Applet {
Button butNext;
Color red = Color.red;
Color orange = Color.orange;
Color green = Color.green;
public void init() {
butNext = new Button("Red");
add(butNext);
public void paint(Graphics g) {
switch(butNext)
case 0:
g.setColor(red);
g.fillOval(100,50,70,80);
break;
case 1:
g.setColor(orange);
g.fillOval(100,50,70,80);
break;
case 2:
g.setColor(green);
g.fillOval(100,50,70,80);
break;
}Appreciate any responses. Thank You :=DI have done the following code but doesn't
like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
I'm guessing it won't compile because you're trying to switch on a Button.
I tried something
like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
Would appreciate it if someone could tell me how to position
shapes using the graohic method. I think the problem is that you're confusing shapes with components. -
Please Help: Trouble with nested CASE statement and comparing dates
Please tell me why the query below is always returning the bold null even when the start_date of OLD is greater than or equal to the start_date of NEW.
What I want to do is get the difference of the start_dates of two statuses ( Start_date of OLD - Start_date of NEW) if
1. end_date of NEW is not null
2. start_date of OLD is greater than start_date of NEW
else return null.
select id,
case when max(end_date) keep (dense_rank last order by decode(request_wflow_status,'New',1,0),start_date) is null then
null
else
case when max(decode(status,'OLD',start_date,null)) > max(decode(status,'NEW',start_date,null))
then max(decode(status,'OLD',start_date,null)) - max(decode(status,'NEW',start_date,null))
else
null
end
end result
from cc_request_status where id =1
group by id;Avinash,
Thank you for your help.. Here is a more description of my problem..
Here is a sample of data I have for a table with four columns (id,status,start_date,end_date)
What I need to do is to get difference of the start dates of the maximum available dates, if data is valid. The pseducode is as follows:
IF end_date of New status is null
THEN return null
ELSE
IF start_date of old >= start_date of new
THEN return (start_date of old - start_date of new)
ELSE return null
I used the following query but always return the bold null
select id,
(case when max(end_date) keep (dense_rank last order by decode(status,'new',1,0),start_date) is null then
null
else
(case when max(decode(status,'old',start_date,null)) >=
max(decode(status,'new',start_date,null))
then max(decode(status,'old',start_date,null)) - max(decode(status,'new',start_date,null))
else
null
end)
end) result
from tbl where id =1
Based on the below sample, I expected to get the following result; 14-Mar-07 - 16-Feb-07 which is the difference of the maximum start_dates of the two statuses. However the query is not working.. Please help me.. Thank you..
Id Status start_date end_date
1 new 03-Feb-07 07-Feb-07
1 new 16-Feb-07 21-Feb-07
1 old '10-Mar-07 12-Mar-07
1 old '14-Mar-07 16-Mar-07 -
Count distinct in case statement
SELECT A.P_ID,
B.P_NAME,
C.P_DESC,
SUM(CASE
WHEN A.DATE BETWEEN TRUNC(ADD_MONTHS(LAST_DAY(SYSDATE),-4) + 1) AND ADD_MONTHS(LAST_DAY(TO_DATE(SYSDATE)),-1)
AND A.M_ID IS NOT NULL
THEN 1
ELSE 0
END) AS COUNT,
SUM(CASE
WHEN A.DATE BETWEEN TRUNC(ADD_MONTHS(LAST_DAY(SYSDATE),-4) + 1) AND ADD_MONTHS(LAST_DAY(TO_DATE(SYSDATE)),-1)
AND A.M_ID IS NOT NULL
THEN COUNT(DISTINCT A.M_ID)
ELSE 0
END) AS UNIQUE_COUNT, /* Not possible */
SUM(CASE
WHEN A.DATE BETWEEN TRUNC(SYSDATE,'YEAR') AND ADD_MONTHS(LAST_DAY(TO_DATE(SYSDATE)),-1)
THEN A.AMT_1
ELSE 0
END) AS TOTAL_AMT_1,
SUM(CASE
WHEN A.DATE BETWEEN TRUNC(SYSDATE,'YEAR') AND ADD_MONTHS(LAST_DAY(TO_DATE(SYSDATE)),-1)
THEN A.AMT_2
ELSE 0
END) AS TOTAL_AMT_2
FROM TABLE_A A,
TABLE_B B,
TABLE_C C
WHERE A.P_ID = B.P_ID
AND B.PT_ID = C.PT_ID
GROUP BY A.P_ID,
B.P_NAME,
C.P_DESC
Hi,
This is a simplified version of my query.
I am trying to do 4 things here,
1. count A.M_ID
2. count distinct A.M_ID, this is where I have a problem.
3. and 4. Its just the sum from 2 diff columns.
Note that the dates for count and amt are different and I can't hard code them.
Can any one help me in the distinct count step?
This query is also running kinda slow.
So any suggestions, comments are very welcome.
Note: TABLE_A has 700 million recs, TABLE_B 4 million and TABLE_c is just 500 recs
Thanks!Taking advantage of the fact that most aggregate functions ignore nulls, you could do something like:
SELECT a.p_id, b.p_name, c.p_desc,
COUNT(CASE WHEN a.date BETWEEN TRUNC(ADD_MONTHS(LAST_DAY(sysdate),-4) + 1) AND
ADD_MONTHS(LAST_DAY(TO_DATE(sysdate)),-1) AND
a.m_id IS NOT NULL THEN m_id END) AS countall,
COUNT(DISTINCT CASE WHEN a.date BETWEEN TRUNC(ADD_MONTHS(LAST_DAY(sysdate),-4) + 1) AND
ADD_MONTHS(LAST_DAY(TO_DATE(sysdate)),-1) AND
a.m_id IS NOT NULL THEN a.m_id END) AS unique_count, /* entirely possible */
SUM(CASE WHEN a.date BETWEEN TRUNC(sysdate,'YEAR') AND
ADD_MONTHS(LAST_DAY(TO_DATE(sysdate)),-1) THEN a.amt_1
ELSE 0 END) AS total_amt_1,
SUM(CASE WHEN A.DATE BETWEEN TRUNC(sysdate,'YEAR') AND
ADD_MONTHS(LAST_DAY(TO_DATE(sysdate)),-1) THEN A.AMT_2
ELSE 0 END) AS TOTAL_AMT_2
FROM table_a a, table_b b, table_c c
WHERE a.p_id = b.p_id and
b.pt_id = c.pt_id
GROUP BY a.p_id, b.p_name, c.p_descThe two case statements inside the COUNT return either a.m_id or NULL. A simplified test case is:
SQL> WITH t as (
2 SELECT 1 m_id, 9 dt FROM dual UNION ALL
3 SELECT 1 m_id, 6 dt FROM dual UNION ALL
4 SELECT 2 m_id, 9 dt FROM dual UNION ALL
5 SELECT 2 m_id, 6 dt FROM dual UNION ALL
6 SELECT 1 m_id, 5 dt FROM dual UNION ALL
7 SELECT 2 m_id, 5 dt FROM dual UNION ALL
8 SELECT null m_id, 9 dt FROM dual)
9 SELECT count(CASE WHEN dt BETWEEN 6 and 9 THEN m_id end) cid,
10 count(distinct CASE WHEN dt BETWEEN 6 and 9 THEN m_id end) cdid
11 FROM t;
CID CDID
4 2I'm not entirely sure that you actually need the a.m_id IS NOT NULL predicate in the CASE statements, but I left it to be safe.
John -
Count Distinct Wtih CASE Statement - Does not follow aggregation path
All,
I have a fact table, a day aggregate and a month aggregate. I have a time hierarchy and the month aggregate is set to the month level, the day aggregate is set to the day level within the time hierarchy.
When using any measures and a field from my time dimension .. the appropriate aggregate is chosen, ie month & activity count .. month aggregate is used. Day & activity count .. day aggregate is used.
However - when I use the count distinct aggregate rule .. the request always uses the lowest common denominator. The way I have found to get this to work is to use a logical table source override in the aggregation tab. Once I do this .. it does use the aggregates correctly.
A few questions
1. Is this the correct way to use aggregate navigation for the count distinct aggregation rule (using the source override option)? If yes, why is this necessary for count distinct .. what is special about it?
2. The main problem I have now is that I need to create a simple count measure that has a CASE statement in it. The only way I see to do this is to select the Based on Dimensions checkbox which then allows me to add a CASE statement into my count distinct clause. But now the aggregation issue comes back into play and I can't do the logical table source override when the based on dimensions checkbox is checked .. so I am now stuck .. any help is appreciated.
KOk - I found a workaround (and maybe the preferred solution for my particular issue), which is - Using a CASE Statement with a COUNT DISTINCT aggregation and still havine AGGREGATE AWARENESS
To get all three of the requirements above to work I had to do the following:
- Create the COUNT DISTINCT as normal (counting on a USERID physically mapped column in my case)
- Now I need to map my fact and aggregates to this column. This is where I got the case statement to work. Instead of trying to put the case statement inside of the Aggregate definition by using the checkbox 'Base on Dimension' (which didnt allow for aggregate awareness for some reason) .. I instead specified the case statement in the Column Mapping section of the Fact and Aggregate tables.
- Once all the LTS's (facts and aggregates) are mapped .. you still have to define the Logical Table Source overrides in the aggregate tab of the count distinct definition. Add in all the fact and aggregates.
Now the measure will use my month aggregate when i specify month, the day aggregate when i specify day, etc..
If you are just trying to use a Count Distinct (no CASE satement needed) with Aggregate Awareness, you just need to use the Logical Table Source override on the aggregate tab.
There is still a funky issue when using the COUNT aggregate type. As long as you dont map multiple logical table sources to the COUNT column it works fine and as expected. But, if you try to add in multiple sources and aggregate awareness it randomly starts SUMMING everything .. very weird. The blog in this thread says to check the 'Based on Dimension' checkbox to fix the problem but that did not work for me. Still not sure what to do on this one .. but its not currently causing me a problem so I will ignore for now ;)
Thanks for all the help
K -
Controlling program flow and case statements
Hey all, I was wondering, I if I have 40 nested case statements and I want the program to close after they are all done, is it sufficient to wire the "?" for both true and false of the outermost case to the close routine in order to guarantee that all of them will execute? Or is there an even better way using data flow methods?
-DobbsI'd recommend state machines better than that way or sequences, to controll dataflow better. Example is attached.
Attachments:
untitled.vi 33 KB
Maybe you are looking for
-
JBuilder 3.1 Deployment/JDBC Exception - Exhausted Resultset
I just installed JBuilder 3.1 with Oracle 8i (8.1.6) on NT workstation w/SP5 and am receiving error "java.sql.SQLException: Exhausted Resultset" upon choosing deploy for sample "Auctions" application profile. I have an idea this has to do with the nu
-
SQL query in powershell Errors on IIF
Hello, I have put together a Powershell script from examples online to run a SQL query. The query came from Access and it seems Powershell has a problem with the syntax. I'm pretty new to scripting and adding SQL to the equation isn't helping. Power
-
Using Function module HR_INFOTYPE_OPERATION
Hi folks, I am using the FM HR_INFOTYPE_OPERATION, in my report. What values i need to pass for the import parameter RECORD. Without passing this parameter, its going to dump...Could any one suggest me how to pass this paramter..or if any sam
-
I am a novice at Aperture (3.1.2) but enjoy using it; and I am a very amateur photographer. A "1st grade" question: I imported some 150 images as a Project. I then went through them and did some sorting into 5 Albums. One of these Albums ended wit
-
Too many broken pipe exceptions
I understand this broken pipe exceptions are caused when the user clicks stop on the browser. However, it seems as if clicking stop once results in dozens of broken pipe exceptions cropping up in the weblogic.l