SQL CASE STATEMENT IMPLEMENTATION
REquirment
• Add indicator to the end of the files, (position 1051 in both extracts, either have value of Y or N).
o DUAL COVERAGE (Y/N)
• Logic to determine indicator values from Member Eligibility Table:
o For ‘Y’ indicator:
o When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID = ‘MD11’ (Mean Dual covered member)
o For ‘N’ indicator:
When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID <> ‘MD11’
• Groups included:
o 100100 (Medicare)
o 100598 (Medicaid-OHP)
• Previous syntax
• select top 20000
• EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
• RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
• a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
• YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
• S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
• P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
• BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
• b.HIOS_NUMBER,
• null as PREMIUM_PAID_DATE,
• null as PREMIUM_PAID_END_DATE,
• b.APTC,
• null as 'GracePeriodIndicatorStartDate',
• null as'GracePeriodIndicatorEndDate',
• null as'ExchangePlanType'
• from Extract_602_603_PBH_Extract_Main a
• left join Extract_602_603_PBH_Extract_HRI b
• on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
Syntax I am trying to implement(taking forever to execute) Please help correct
select distinct
EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
b.HIOS_NUMBER,
null as PREMIUM_PAID_DATE,
null as PREMIUM_PAID_END_DATE,
b.APTC,
null as 'GracePeriodIndicatorStartDate',
null as'GracePeriodIndicatorEndDate',
null as'ExchangePlanType',
case when MEPE.CSCS_ID = 'MD11' AND grgr.GRGR_ID IN('100100','100598')
THEN 'Y'
ELSE 'N' end as DualCoverageIndicator
from Extract_602_603_PBH_Extract_Main a
left join Extract_602_603_PBH_Extract_HRI b
on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
join FacetsReport.dbo.CMC_MEPE_PRCS_ELIG MEPE
ON a.CLASS_ID= MEPE.CSCS_ID
Join FacetsReport.dbo.CMC_GRGR_GROUP grgr
ON MEPE.GRGR_CK= grgr.GRGR_CK
>on LEFT(a.MEMBER_NO,7)
=b.SBSB_ID
This is not a good JOIN. It is not SARGable:
http://www.sqlusa.com/bestpractices/sargable/
Can you post table/index DDL? Thanks.
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014
Similar Messages
-
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 -
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 -
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 -
Hello, just starting to learn PL/SQL. I have a query which runs just fine and it has a case statement. When I take that query and place it into a procedure and compile, it gives me a compile error stating "ENCOUNTERED symbol CASE when expecting... providing a list of symbols.
This procedure is part of a package, so I am only showing the procedure portion...
PROCEDURE QRY_USERS (oRows OUT t_cursor)
IS
BEGIN
OPEN o_Rows FOR
select ou.User_id,
ou.AD_Login_ID,
ou.First_name,
ou.Last_Name,
oct.CODE_DESC,
case when ou.deleted is null then 'N'
else 'Y' end Deleted
from tst_ops_users ou, tst_ops_code_tbl oct
where oct.CODE_TYPE ='USER_TYPE'
and oct.code_name = ou.USER_ROLE_TYPE;
END QRY_USERS;
So is there some different syntax with case statements or is there some other erro causing this?
Thanks a bunch for your assistance!!!Which version of the database are you working on? In 8i the PL/SQL engine did not support the use of CASE in SQL statements (along with a whole bunch of other fresh additions to SQL syntax).
If that is your problem you could try this, which ought to use the SQL engine instead...
PROCEDURE QRY_USERS (oRows OUT t_cursor)
IS
BEGIN
OPEN oRows FOR
'select ou.User_id,
ou.AD_Login_ID,
ou.First_name,
ou.Last_Name,
oct.CODE_DESC,
case when ou.deleted is null then ''N''
else ''Y'' end Deleted
from tst_ops_users ou, tst_ops_code_tbl oct
where oct.CODE_TYPE =''USER_TYPE''
and oct.code_name = ou.USER_ROLE_TYPE';
END QRY_USERS;although you can obviate the need for CASE by using either DECODE or NVL2...
nvl2(ou.deleted , 'Y', 'N') AS deletedCheers, APC -
Hi,
could you please advise how to add below New case to below Main case
New case:
when (convert(varchar,date,101) >= '01/01/2014' OR qtr >= '14Q1') then
case when PP='ABC' and pl='EFG' then Revenue*.552
else 0 end
Main case:
SUM(
case
when ((convert(varchar,date,101)>= '09/19/2013' and qtr = '13Q3') OR qtr >= '13Q4') then
case when PP='ABC' and pl='EFG' then Revenue*.542
else 0 end
when (convert(varchar,date,101) < '09/19/2013' OR qtr < '13Q3') then
case when PP='ABC' and pl='EFG' then Revenue*.501
else 0 end
else 0 end) revenue,There is no CASE statement in SQL; we have CASE expression. AND you got the syntax wrong. SQL uses the ISO-8601 date format; it is one of the most basic ISO Standards on Earth AND you should know it. But worse than that, you are still using the 1970's
Sybase CONVERT string function! NO! Did you know that DATE is a reserved word in SQL AND cannot be a column name?
When we design a code for temporal units like Quarters, we follow the ISO-8601 as closely as possible. That means a full four-digit year.
Since you were rude AND did post DDL, I will guess that your improper “date” is a TIMESTAMP (aka DATETIME or DATETIME2(n) in Microsoft dialect).
>> could you please advise how to add below New CASE to below Main CASE <<
I never heard the term “main CASE”, even when I voted on this feature. Can you explain it to me and show where I missed it?
The quarters are temporal computations; we would not put them in a base table, but a good SQL programmer would use a VIEW with a join to a report period table.
CASE WHEN CAST (foobar_timestamp AS DATE) >= '2014-01-01'
OR foobar_qtr > = '2014Q1'
THEN CASE WHEN pp = 'ABC'
AND pl = 'EFG'
THEN something_revenue * 0.552
ELSE 0.000 END;
I will assume that pl and pp well-understood terms in your industry and not improper data element names. Why did you nest CASE expressions? Let me answer that: you think that CASE is IF-THEN-ELSE statements!
Did you notice that an event during '2014Q1' is always BETWEEN '2014-01-01' AND '2014-03-31'? So this is redundant!
A minor point, it is good idea to use a leading zeroes and decimal zeroes to show the guy maintaining code what he is working with. It also helps the compiler avoid casting. Your expression also has no name.
CASE WHEN CAST (foobar_timestamp AS DATE) > = '2014-01-01'
AND pp = 'ABC'
AND pl = 'EFG'
THEN something_revenue * 0.552
ELSE 0.00 END AS nameless_floob;
I am afraid that you might have re-discovered the Algol-60 dangling ELSE problem. As with Algol-60, the ELSE in SQL associates with the nearest CASE. Not with the outermost CASE.
Your expression ought to have this skeleton:
SUM(CASE WHEN ???
THEN something_revenue * 0.542
WHEN ???
THEN something_revenue * 0.501
WHEN ???
THEN something_revenue * 0.552
ELSE 0.000 END)
AS something_revenue_tot
--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 -
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 -
Need some help with a case statement implementation
I am having trouble using a CASE statement to compare values and then display the results. The other issue is that i want to put these results in a separate column somehow.
Heres how the code would look:
SELECT "Task"."Code",
"Stat" = CASE WHEN "Task.Code" = 1 THEN string
....and so on
I wanted to make "Stat" the new column for the results, and string represents the string to be assigned if 1 was the value for code. I keep getting syntax error, any help would be nice.This is a lot easier than you might think.
1) First, move another column of "Code" to your workspace.
2) Click on the fx button and then on the BINS tab.
3) Click on "Add BIN" and with the operand on "is equal to/is in," input 1 and then click "OK."
4) Name this what you had for "string."
Repeat for all the different values you want to rename as another "string" value.
5) Finally, check the "custom heading" checkbox, and rename this column "Stat" as you indicated.
That's it. -
SQL Case Statement Problem with Maxdb
Hello,
I'm running a J2E application on Netweaver AS. I have on problem that I just cannot figure out.
The statement works in SQL Studio but when I try to code it it does not work at all.
select COLA, SUM(CASE WHEN COLB=10 THEN 1 ELSE 0 END) from TABLE group by COLA
When executed as statement in Java I get:
Error [javax.servlet.ServletException: java.lang.IllegalStateException: illegal stack size: 4
contents:
com.sap.sql.tree.SelectStatement
com.sap.sql.tree.IntegerLiteral
com.sap.sql.tree.IntegerLiteral
com.sap.sql.tree.ComparisonPredicate], with root cause [java.lang.Exception: java.lang.IllegalStateException: illegal stack size: 4
contents:
com.sap.sql.tree.SelectStatement
com.sap.sql.tree.IntegerLiteral
com.sap.sql.tree.IntegerLiteral
com.sap.sql.tree.ComparisonPredicate].
Any thoughts on that? Thanks!
Edited by: MD on Feb 18, 2009 7:37 PMHi MD,
with SQL Studio you mean you work with MaxDB?
Are you sure you're working directly on MaxDB and not with OpenSQL? (That's different!)
If you want the first, try setting SQL type "vendor" or "native sql". In such case you have to define a new custom datasource through configuration. How that works depends on the version you are using.
Try to find out what the actual error message is. The stack trace is not enough. There should be more.
Regards,
Benny -
SQL Case statement Help....
Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
I have got that with the below SQL:
Count of Overrides =
select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
But now i have to look at two columns and get the count()
I have
col_1 and col_2 in table_1 and
col_3 and col_4 in table_2
(I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
Will the following SQL return correct values?
Count of Overrides =
Select
Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
Thanks"yes, it can be rewritten as a decode. but why bother?"
Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
SQL> WITH t AS (
2 SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
3 SELECT 1, 1, 2, 3 FROM dual UNION ALL
4 SELECT 1, 2, 3, 3 FROM dual UNION ALL
5 SELECT null, 1, 2, 2 FROM dual UNION ALL
6 SELECT 1, 1, 2, null FROM dual UNION ALL
7 SELECT 1, 2, 3, 4 FROM dual)
8 SELECT col_1, col_2, col_3, col_4,
9 CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
10 DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
11 FROM t;
COL_1 COL_2 COL_3 COL_4 OCASE O
1 1 2 2
1 1 2 3 1 1
1 2 3 3 1 1
1 2 2 1
1 1 2 1
1 2 3 4 1 1John -
Hello All,
I have a query similar to the one below. I have to use a Custom SQL DB adapter to achieve this. When i create a variable I get four variables in the input payload (two for Param1 and two for Input). I was wondering if we can avoid this, because this is like duplicity and we have to populate the values twice each (I know this can be achieved by a Procedure, but we have a restriction).
SELECT CASE
WHEN #param1 = 'P1'
THEN (SELECT col1
FROM table1
WHERE col2 = #input)
END column1,
CASE
WHEN #param1 = 'P2'
THEN (SELECT col1
FROM table2
WHERE col2 = #input)
END column2,
FROM DUAL;
The input collection is as shown below.
<xs:complexType name="compiste_queryInput">
<xs:sequence>
<xs:element name="param1" type="xs:string" nillable="true"/>
<xs:element name="input" type="xs:string" nillable="true"/>
<xs:element name="param1" type="xs:string" nillable="true"/>
<xs:element name="input" type="xs:string" nillable="true"/>
</xs:sequence>
</xs:complexType>
Any help is much appreciated.
Thanks
KrishnaHi Krishna,
I think this is a limitation. Actually it creates an element in xsd for each bind parameter and won't allow having 2 elements with the same name inside the xsd.
The one given by you also will report a compile time error as it is using #param1 and #input twice.
You need to change them to param1, param2 etc. and copy the same values to each.
Appreciate if anyone can post a workaround for the same.
Regards,
Neeraj Sehgal -
Sql case statement for parametes
I am using sort parameters in the stored procedure
the following is my case statment
CASE When @SORT_1 = 'CUSTOMER'
Then ar_ivhdr_tbl.EN_CUST_KEY
When @SORT_1 = 'BILLTO'
Then ar_bill_tbl.ar_bill_name
Else ' ' END SORTKEY
what i would like to do is
have the sort key sort by 2 fields so instead of just the customer sort sorting the customer field
i would like it to sort customer and bill to
this is the syntax i tried but sql doesnt like it
CASE When @SORT_1 = 'CUSTOMER'
Then ar_ivhdr_tbl.EN_CUST_KEY,ar_bill_tbl.ar_bill_key
When @SORT_1 = 'BILLTO'
Then ar_bill_tbl.ar_bill_name, date
Else ' ' END SORTKEY
syntax issues, any ideas?Hi Sharon,
Your syntax is off. Not sure what database you are using by it should look something like:
CASE @SORT_1
When 'CUSTOMER' Then ar_ivhdr_tbl.EN_CUST_KEY,ar_bill_tbl.ar_bill_key
When 'BILLTO' Then ar_bill_tbl.ar_bill_name, date
Else ' '
END
Good luck,
Brian -
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 script into a CASE statement ?
Hy,
can someone tell me, please, if is it possible insert into a case statement (shell unix script) one or more SQL script ?
For example :
case aaa in
1 )
sqlplus blabla <<!
update ...
insert ...
2 )
esac
Thank you very much !
Andys/unix/sqlplus -s username/pwd @file_name.sql
This will work on unix prompt. use this in shell script and implement. file_name.sql containts update logic.
I hope it will solve ur problem.
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Andys:
Hy,
can someone tell me, please, if is it possible insert into a case statement (shell unix script) one or more SQL script ?
For example :
case aaa in
1 )
sqlplus blabla <<!
update ...
insert ...
2 )
esac
Thank you very much !
Andys<HR></BLOCKQUOTE>
null -
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
Maybe you are looking for
-
How do I retain Microsoft Word hyperlinks (internal to the Word document) in pdf export? I lose them in process. Using Word 2011 (14.4.3) and Mavericks. Have tried importing to Pages 5.2 and exporting, but that does not work either.
-
My phone C3-00 is running on latest update v08.71 but I'm unable to use Nokia pre-installed apps via Wi-Fi like Mail, Communities, etc, except the Chat service. When I start any app like Mail it asks for connection via Wi-Fi or SIM, I choose Wi-Fi, t
-
HT1386 synch podcasts from computer to IPAD
I am having trouble syncing my podcasts from my PC laptop to my IPad II. Before the latest versions of Itunes, one could download a podcast onto the IPAD and then easily "get the newest episode" but now that option has gone away. I can renew podcas
-
People contacting me not in my contacts
Recently in the last couple months I have had random people send me messages to become a contact. I do not know these people so I block them. My privacy settings are set to contacts only so how can I stop this?
-
Advantage of SQL Query (Strucutred Query) over SQL Query
What is the advantage of a Region Type 'SQL Query (Structured Query)' over 'SQL Query'? I just became curious when comparing the results of the Master Detail Wizard, and the Report and Form Wizard.