Case statement in advanced sql
how to use case statement in advanced sql.Example if quarter=1 i need to select jan,fev,and march months from table
this is the case statement i am using :
case when 1=@{quarter} then substring(cast((etxnmis.month_year) as char) from 5 for 2) IN ('03', '04', '05') else null end
and i get the below error
: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near <IN>: Syntax error [nQSError: 26012] . (HY000)
Similar Messages
-
Case statement in Advanced SQL filter
Hi,
I have two columns Vendors and their Sales
Vendor| Sales
------- | ---------
|
Sales is a measure. I have 4 more measures like this (sales, products, units etc). I need to create a report with two columns (one column is vendor and the other column is a measure) so that the second column changes dynamically on the dashboard. I can acheive this using Column selector. But my requirements demands to have TOPN prompt so that only top N vendors should display. Hence I created a presentation variable and mimcked the column selector functionality with a "Dashboard prompt as Column selector" (google dashboard prompt as column selector to verify how a dashboard prompt can be used as a column selector).
So finally I created a dummy column with Rank Function and arranged it in ascending order and applied the filter as (less than or equal as to the presentation variable)
so when we plug in, lets say, 5 the filter will apply to the Rank column and display the TOP 5 vendors.
Now, the real problem is...one of the measures requires the bottom 5 to display since the TOPN for that measure is calculated in descending order.
Hence in the filter I gave
Case when presentation variable = "measure" then bottomN else TOPN.... but it is returning an error...
Can you guys help me on this issue. If you dont understand the query exactly please ping me....hi,
try a simple one...
use your function with a variable....pass manually a number let's say 5...what's your results??with a sort getting better??
then try to see the report with presentaion variable..
hope i helped...
http://greekoraclebi.blogspot.com/ -
How to create nested CASE statements in PL/SQL
Can anyone please tell how to create Nested CASE statements in PL/SQL with proper syntax?
It would be better if you can help with an example.
Thank you!Something like this:
SQL> set serveroutput on
SQL> declare
2 v1 number := 2;
3 v2 varchar2(1) := 'C';
4 begin
5 case v1
6 when 1 then dbms_output.put_line('First');
7 when 2 then begin
8 case v2
9 when 'A' then dbms_output.put_line('Found A');
10 when 'B' then dbms_output.put_line('Found B');
11 when 'C' then dbms_output.put_line('Found C');
12 else dbms_output.put_line('NONE');
13 end case;
14 end;
15 else dbms_output.put_line('Else');
16 end case;
17 end;
18 /
Found C
PL/SQL procedure successfully completed
SQL> If you have further doubts regarding syntax you can read the docs on the Case statement here:
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/case_statement.htm -
Hi PL/SQL experts,
I'm going a bit loopy here, so could someone please point out what I'm doing wrong with this case statement:
Test procedure is:
CREATE OR REPLACE procedure SCOTT.postcode_validate_2 (input_post_code VARCHAR2) as
alphabet_string VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxwyz';
number_string VARCHAR2(10) := '012345789';
last_part_postcode VARCHAR2(3) := NULL;
BEGIN
IF INSTR(input_post_code,' ') = 0
THEN
DBMS_OUTPUT.PUT_LINE('We need a space in the postcode please');
GOTO exit;
ELSIF LENGTH(SUBSTR(input_post_code,instr(input_post_code,' ')+1)) > 3
THEN
DBMS_OUTPUT.PUT_LINE('Last part of postcode can only be 3 characters');
GOTO exit;
ELSE
last_part_postcode := SUBSTR(input_post_code,instr(input_post_code,' ')+1);
END IF;
CASE input_post_code
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 2
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A99')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9A')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9A');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(number_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA99')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(alphabet_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9A')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9A');
-- GOTO exit;
-- END IF;
END;
-- Check last part of format, should be AA9
IF (instr(number_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the correct format, 9AA');
ELSE
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the wrong format!');
END IF;
<<exit>>
DBMS_OUTPUT.PUT_LINE('Please try again');
END;
However, I'm getting the following error:
LINE/COL ERROR
37/6 PLS-00103: Encountered the symbol "WHEN" when expecting one of
the following:
:= . ( % ;
On a second note, can I not have the ELSE structure embedded within the case (currently commented out)?
Thanks very much in advance.
DevFixed code:
CREATE OR REPLACE procedure postcode_validate_2 (input_post_code VARCHAR2) as
alphabet_string VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxwyz';
number_string VARCHAR2(10) := '012345789';
last_part_postcode VARCHAR2(3) := NULL;
BEGIN
IF INSTR(input_post_code,' ') = 0
THEN
DBMS_OUTPUT.PUT_LINE('We need a space in the postcode please');
GOTO exit;
ELSIF LENGTH(SUBSTR(input_post_code,instr(input_post_code,' ')+1)) > 3
THEN
DBMS_OUTPUT.PUT_LINE('Last part of postcode can only be 3 characters');
GOTO exit;
ELSE
last_part_postcode := SUBSTR(input_post_code,instr(input_post_code,' ')+1);
END IF;
CASE
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 2
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A99');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9A');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9A');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(number_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA99');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(alphabet_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9A');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9A');
-- GOTO exit;
-- END IF;
END CASE;
-- Check last part of format, should be AA9
IF (instr(number_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the correct format, 9AA');
ELSE
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the wrong format!');
END IF;
<<exit>>
DBMS_OUTPUT.PUT_LINE('Please try again');
END;
/As VG2 pointed out you were missing some semicolons.
Also, CASE input_post_code was replaced with just CASE since you are doing a searched case.
Also, END at the end of the case statement was replaced with END CASE. -
Multiple case statements with aggregates- SQL
Hi guys
Here is my ddl
create table TestTable
Bill_date DATE,
Phone_no NUMBER(10),
Planlvl1 VARCHAR2(20),
Planlvl2 VARCHAR2(20)
Revenue NUMBER
INSERT INTO TestTable
Values
('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014'' , 64221, 'Bundle', 'PlanA', '$32'),
('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
Expected Outcome:
Bill_date PlanLvl2 PhonenoCount
'01/01/2014' 'SpecialPack1' 1
'01/01/2014' 'SpecialPack2' 3
'01/01/2014' 'Casual1' 1
'01/01/2014' 'Casual2' 1
'01/01/2014' 'PlanA' 1
'01/01/2014' 'PlanB' 1
Basically I have to count all the phone nos grouped by plans in a certain way:
If PlanLvl1 = Bundle, then I have to look at planLvl2 and see if that phone no has ' SpecialPack%' ,and also another plan,them 'Special pack' gets the priority and the phone no gets counted in the special pack.
In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue.
In case where PalnLvl is 'Bundle' and a phone no has multiple 'Special Packs' and a non special, that ph no will only be counted once under 'Special Pack; of higher rev as compared to the special pack of lower rev.
Now there are also PlanLvl1 which are 'Non_Bundles' which means they do not have any 'SpecialPacks' but if a ph no with 'NonBundle' plan has 2 different plans under planLvl2, we need to count that ph no for eack planLvl2..
Then there is a scenario where a ph no can have bundles as well as non bundles and in that case we just have to count that ph no in bundles and not in non-bundles.
As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these
Hope this helpsI;m not sure exactly what your rules are since you specify both "In case when PlanLvl1 = Bundle and a phone no has both 'Special Packs' as their plans, then the phone no will be counted under the 'Special Pack' with higher Revenue" and "As I mentioned ,
'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these". I went with the rule "As I mentioned , 'SpecialPack2' will get a preference over special pack 1 if a phone no has got both of these" since that seemed to match
the result you say you want. I also changed the datatypes to valid SQL Server datatypes.
create table TestTable
Bill_date DATE,
Phone_no Decimal(10,0),
Planlvl1 VARCHAR(20),
Planlvl2 VARCHAR(20),
Revenue money
INSERT INTO TestTable
Values
('1/01/2014' , 64221, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014' , 64221, 'Bundle', 'PlanA', '$32'),
('1/01/2014' , 65211, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 65211, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014' , 66211, 'Bundle', 'PlanB', '$34'),
('1/01/2014' , 66211, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 66222, 'Bundle', 'SpecialPack1', '$23'),
('1/01/2014' , 66222, 'Bundle', 'SpecialPack2', '$3'),
('1/01/2014' , 66222, 'Bundle', 'PlanB', '$65'),
('1/01/2014' , 32444, 'Non_bundle', 'Casual1', '$32'),
('1/01/2014' , 324441, 'Non_bundle', 'Casual2', '$76'),
('1/01/2014' , 65444, 'Non_bundle', 'Casual1', '$12'),
('1/01/2014' , 65444, 'Bundle', 'PlanB', '$98'),
('1/01/2014' , 54322, 'Bundle', 'PlanA', '$12'),
('1/01/2014' , 54322, 'Non_bundle', 'Casual', '$12')
;With cte As
(Select Bill_date, Phone_no, Planlvl1, Planlvl2, Revenue,
Row_Number() Over (Partition By Bill_Date, Phone_no Order By
Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack2' Then 0 Else 1 End,
Case When Planlvl1 = 'Bundle' And Planlvl2 Like 'SpecialPack1' Then 0 Else 1 End,
Case When Planlvl1 = 'Bundle' Then Revenue Else -1 End Desc) As rn,
Min(Case When Planlvl1 = 'Bundle' Then 0 Else 1 End) Over(Partition By Bill_Date, Phone_no) As NumberHasOnlyNonBundle
From TestTable)
Select Bill_date, Planlvl2, COUNT(*) As PhoneNoCount
From cte
Where rn = 1 Or NumberHasOnlyNonBundle = 1
Group By Bill_date, Planlvl2;
Tom -
Just a FYI regarding Case statements in ORacle 8i in pl/sql
Well..I saw numerous posts in this forum regarding not being able to do case statement within pl/sql. Well..you can do
that using dynamic SQL. IT works like a champ.Hi,
Try first to (re)compile ll invalid objects. then
you can run:
select owner,type,count(*) from all_errors
group by owner,typeif you still have uncompiled objects, then report the different errors:
select * from all_errors... -
SSIS: Using CASE Statement Within A Derived Column Transformation Expression
The following is my Data Flow:
Ole DB Source > Copy Column > Derived Column >Ole DB Command
My OLE DB Source has the following SQL command task:
SELECT *
FROM Repair R
LEFT OUTER JOIN Vehicle V
ON R.SN = V.SN
AND R.Reg = V.Reg
LEFT OUTER JOIN Product P
ON R.PID = P.PID
This yields a column of concern for me named PartNumber, which are represented by the following 2 formats:
The following are my Copied Columns:
Input Column = PartNumber
Output Alias = Copy of PartNumber
The following are my Derived Column expressions:
Derived Column Name Derived Column Expression
Name Replace 'PartNumber' LEFT(PartNumber,FINDSTRING(PartNumber,"-",1) - 1)
Copy of Name Replace 'Copy of PartNumber' RIGHT([Copy of PartNumber],LEN([Copy of PartNumber]) - FINDSTRING([Copy of PartNumber],"-",1))
So My PartNumber Column is Replaced with ######### of type
string and the Copy of PartNumber column is replaced with
#### of type int
As I stated earlier PartNumber also is in the format of %-%-% which raises the following question:
How can I replace PartNumber Column with NULL if in format of
%-%-% and take the PartNumber and put it in new column named
SubPart while keeping all the logic within SSIS objects?
So in essence I want to do something like the following:
PartNumber = CASE
WHEN 'PartNumber' LIKE '%-%-%'
THEN ABC = PartNumber AND PartNumber IS NULL
END
I have tried the case statement in a Derived Column expression and is not working. Would I add the
CASE statement to the SQL command task in my OLE DB Source?
I hope this question is concise for you.If it must be in SSIS, I would put a derived column stage earlier in the process to do my check for me. Then in the second derived column stage do the check against each output column (part, subpart, copy of part) to decide which way it goes
PS Not sure if it's a 2012 function but SSIS has a function called TOKEN that will allow you to pull your subparts for you rather than the left/right you are doing -
I'm trying to use a CASE statement in Ora 8.1.7 (with compatible
set to 8.1.0) and am finding that I cannot compile the
procedure.
I'm using the CASE statement in a call to a procedure...
insert_addr (p_id_number => v_id_number,
p_addr_type => v_addr_type,
p_addr_status => v_addr_status,
p_addr_pref_ind => v_pref_addr_ind,
p_date_modified =>
(CASE
WHEN cmf_rec.hadoc = cnv_constants.nov17_1958
THEN cmf_rec.doe
ELSE cmf_rec.hadoc
END)
I'm getting "PLS-00103 Encountered the symbol "CASE" when
expecting one of the following..." error msg when compiling.
What have I done wrong? Syntax error? Should I change the
compatible parameter?
Thanks.You can actually use the CASE statement in Pl/Sql, though not like in SqlPlus.
You have to use dynamic Sql.
Example
create or replace procedure test_case1 is
v_sql varchar2(4000);
begin
v_sql := 'update case_test set qual_rule = '||
'(case '||
' when dob < ''01-jan-1902'' then ''100+'' '||
' when dob between ''01-jan-1902'' and ''31-dec-1912'' then ''90-99'' '||
' when dob between ''01-jan-1912'' and ''31-jan-1932'' then ''70-89'' '||
' when dob between ''01-jan-1932'' and ''31-jan-1952'' then ''50-69'' '||
' when dob between ''01-jan-1952'' and ''31-jan-1972'' then ''30-49'' '||
' when dob between ''01-jan-1972'' and ''31-jan-1984'' then ''< 30'' '||
' else ''under age'' '||
' end ) ';
execute immediate v_sql;
commit;
end test_case1; -
Can CR 2008 with XML ODBC driver using SQL CASE statement?
Hi:
when i use SQL Command to provide data to the report from XML file connection. I can not use CASE statement , CR always has error message about "CASE" word.
I test the same Statement in SQL client connected to Oracle, it runs fine.
So.. Is it driver's limitation that XML datasource can not use CASE statement inside SQL command window?
Thanks anyone's reply in advance.
JohnnychiHi Johnny,
CR supports what every the ODBC driver supports. The error you are getting is from the XML driver, CR is just passing it through.
Try using an ODBC to XML driver and then a stand-alone ODBC test tool to see if your SQL works.
If not you'll have to find another way to use the CASE statement.
Thank you
Don -
SQL Expression in decode function or case statement?
Can I put SQL expressions in decode function or case statement?
For example,
select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
from element le;
or
select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
ELSE 'Y'
from element le;
None of the above work.
Can anyone tell me how to make it work?
Is there any workaround?
Thanks,
JYou simply needed and END to your CASE statement;
SQL> with profile_data as (
select 'XXXX_AFTER' name, 1 object_id from dual),
element as (
select 1 profile from dual union all
select 2 from dual)
select le.profile,
case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
THEN 'N'
ELSE 'Y'
END new_col
from element le
PROFILE N
1 Y
2 N -
T-sql case statement in a select
When I execute the following t-sql 2012 statement, the "NO Prod' value is not
being displayed from the sql listed below:
SELECT DISTINCT
IsNull(cs.TYPE,'') as type,
CASE IsNull(Course.TYPE,'')
WHEN 'AP' then 'AP Prod'
WHEN 'IB' then 'IB Prod'
WHEN 'HR' then 'HR Prod'
WHEN '' then 'NO Prod'
END AS label
FROM CustSection cs
INNER JOIN dbo.Person p on P.personID = cs.personID
Left join customCustomer cs564 on cs564.personID = p.personID and
cs564.attributeID ='564'
where ( cs.type is null and cs564.attributeID = null)
or
(cs.type IN ('HR','AP') OR
(cs.type='IB' AND SUBSTRING(cs.code,1,1)='3'))
ORDER BY label
What I want is for 'NO Prod' to be displayed when
cs.type is null and cs564.attributeId is null.
Thus can you tell me how to fix query above so the 'NO Prod' value is displayed in the
select statement listed above?There is no CASE statement in SQL; we have a CASE expression. We do not use the old 1970's Sybase*- ISNULL(); we have COALESCE().
There is no such thing as a magic generic “type” in RDBMS. There is no such thing as a generic “code” in RDBMS. They have to to be “<something in particular>_type” and “<something in particular>_code” in a valid data model. How about blood_type
and postal_code??
There is no such thing as a generic “person” table in RDBMS. First of all, do you really have only one person, as you said?? But the important point is that these persons play a role in the data model – customers, students, etc. You are doing the wrong thing
and doing it badly. This table should not exist any more than a table of “Things” such exist.
And the reason you are beyond any real help is “attribute_id” which tell us that your schema is a total disaster of data and meta data mixed together in a non-RDBMS written in awful SQL. Based on cleaning up bad SQL for 30 years, it looks like you are an OO
programmer who never unlearned his prior mindset.
Why did you allow an encoding schema with blanks? Why do you have so many NULL-able columns?
SELECT DISTINCT is very rare in a properly designed schema. The DRI references assure that rows cam be matched. To get you started, look at this skeleton:
CREATE TABLE Products
(product_gtin CHAR(15) NOT NULL PRIMARY KEY,
product_type CHAR(2) DEFAULT 'XX' NOT NULL
CHECK (product_type IN ('AP', 'IB', 'HR', 'XX'))
The table name is a plural noun because it models a set (NOT an OO class).
The GTIN is an industry standard identifiers, and not have to invent our own.
The product_type (not blood_type, not automobile_body_type!) has a constraint that assures it is never NULL and never blank; I invented 'XX' as a default.
You need more help than you can get in a forum, but if you will follow Netiquette and post the DDL, we can get you started.
--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 -
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. -
SQL CASE statement in XML template- End tag does not match start tag 'group
Hi All,
I am developing a report that has the SQL CASE statement in the query. I am trying to load this into RTF with report wizard and it gives me below error
oracle.xml.parser.v2.XMLParseException: End tag does not match start tag 'group'
Does XML publisher support CASE statement?
My query is something like this
SELECT customercode,
SUM(CASE WHEN invoicedate >= current date - 30 days
THEN balanceforward ELSE 0 END) AS "0-30",
SUM(CASE WHEN invoicedate BETWEEN current date - 60 days
AND current date - 31 days
THEN balanceforward ELSE 0 END) AS "31-60",
SUM(CASE WHEN invoicedate < current date - 60 days
THEN balanceforward ELSE 0 END) AS "61>",
SUM(balanceforward) AS total_outstanding
FROM MyTable
GROUP BY customercode
ORDER BY total_outstanding DESC
Please advice if the CASE statement or the double quotes are causing this error
Thanks,
PPI got this to work in the XML but the data is returning zeros for all the case statements. When I run this in toad I get results for all the case conditions but when ran in XML the data displayed is all zeros. I am not sure what I am missing. Can someone shed some light on this please
Thanks!
PP -
I am working on a project for ambulance response times. In
the following query which is in my coldfusion code, I am using a
CASE statement on a subquery to count the ambulance response times
in bins. An ambulance should arrive at an emergency incident in
less than 8:59 (539 seconds) or else it is considered late. In my
coldfusion Transact-SQL code I am:
1.) doing a subquery.
2.) counting the 'event numbers' based on the time it took
for the ambulance to arrive.
3.) only counting Lee County ambulances and excluding A6 type
calls (non-emergencies).
4.) grouping it by the dateparts.
SELECT DATENAME("M", I.I_tTimeDispatch) as mths,
(DATEPART("yyyy", I.I_tTimeDispatch)) AS yr,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) BETWEEN 0 AND 539 THEN evnt END) AS OnTime,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) BETWEEN 540 AND 1028 THEN evnt END) AS Late,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) > 1028 THEN evnt END) AS Outlier
FROM (SELECT I_EventNumber AS evnt, I_tTimeDispatch,
I_tTimeArrival, I_kTypeInfo, I_Agency FROM dbo.IIncident) as I
INNER JOIN dbo.ITypeInfo AS T ON I.I_kTypeInfo =
T.ITI_TypeInfo_PK
WHERE I.I_Agency='LC'
AND T.ITI_TypeID NOT LIKE 'A6*'
GROUP BY (DATEPART("M", I.I_tTimeDispatch)), (DATENAME("M",
I.I_tTimeDispatch)), (DATEPART("yyyy", I.I_tTimeDispatch))
ORDER BY (DATEPART("yyyy", I.I_tTimeDispatch)) ASC,
(DATEPART("M", I.I_tTimeDispatch)) ASC
Here is my problem!
I go into Microsoft Access to verify my statistics and I get
different counts. For instance, in April 2008 my coldfusion query
returns 3,944 on-time ambulance responses. My Access query for the
same time period using only Lee County ambulances and excluding A6
non-emergencies returns only 3,805 responses. This is an undercount
of 139 responses. Even for my other time bins I am getting an
undercount.
Here is my Access SQL for the on time response bin (<539
seconds or 8:59):
SELECT Count(dbo_IIncident.I_EventNumber) AS
CountOfI_EventNumber
FROM dbo_IIncident INNER JOIN dbo_ITypeInfo ON
dbo_IIncident.I_kTypeInfo = dbo_ITypeInfo.ITI_TypeInfo_PK
WHERE (((dbo_IIncident.I_Agency)="lc") AND
((dbo_ITypeInfo.ITI_TypeID) Not Like "a6*") AND
((dbo_IIncident.I_tTimeDispatch) Between #4/1/2008# And #5/1/2008#)
AND
((DateDiff("s",[dbo_IIncident]![I_tTimeDispatch],[dbo_IIncident]![I_tTimeArrival]))
Between 0 And 539));
How could two queries that are supposed to be doing the same
thing return such different results?
To clear up any confusion I am temporarily posting the page.
Please look at it because it may help you visualize the problem.
http://lcfcfn01/Secure/GTandLT_8_59.cfmThank you for your quick reply.
I thought about that, but it isn't what is causing the
discrepancy in the numbers. This is because Access is hitting the
SQL Server through ODBC. The time stamps in SQL Server are ODBC
datetime stamps so they look like this: 4/19/2008 6:20:18 PM
When my query uses the date #5/1/2008# it is like saying May
1, 2008 00:00:00. Please correct me if I am wrong. The query won't
return any results from May 1, 2008 because it stops at zero
hundred hours. I believe it will only go to April 30, 2008 23:59:59
and then stop there.
I do try and play with the date ranges and the 'seconds'
(<539 or >539) parameter and I consistently get different
results from what my coldfusion page is telling me.
David -
Sql case statement with link not opening new window
Apex 4.2
I am writing a query that has a case statement. I need the case statement to open up a new window, not a new tab. I have the following:
SELECT
case when SCHED_ID = 1 then
'<a href="javascript:popupURL(''http://www.google.com'')">LINK</a>'
end as MyLink
FROM Table_Name
When I plug this into a a column link in the URL field under a page item or report item, then a popup window appears. However, inside the query I am getting a new tab.
ANy help on this matter would be great. Thanks in advance.Hi,
Try adding a target attribute to you link:
'<a href="javascript:popupURL(''http://www.google.com'')" target="_blank">LINK</a>'
Regards,
Vincent
Maybe you are looking for
-
Exactly how does one print to a PDF file from safari on an ipad4?
-
Dreamweaver CS5 11.0.3 Update Won't Install
Hello, I have the Adobe CS5 Web Premium that I use at work. Adobe Application Manager popped up with a Dreamweaver update (11.0.3). I downloaded it and it tries to install but it won't. I run the Support Advisor but it detects no problems. I've never
-
Photo Booth Freezes after upgrading to OS X Yosemite Wifi drops, iMac lags!
Photo Booth Freezes after upgrading to OS X Yosemite Wifi drops, iMac lags!
-
Solaris 9 DS5.1 SP2 Patch: where?
Hi all, I couldn't find the appropriate patch to update the Directory Server 5.1 bundled with Solaris 9 to service pack 2. In all documentation they're referring to a patch id 113859-01, but the patchfinder on sunsolve.sun.com says this is an invalid
-
My printer stopped duplexing how can I restore it
My printer was duplexing now it has stopped how can I get it to work again