Oracle PL/SQL/Select Query/Case Query — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 13:45, 26 мая 2010
Содержание
- 1 A searched CASE statement
- 2 case switch based on clob data
- 3 case when count(*) NOT between ... and
- 4 Combine Case with group by
- 5 Combine case with NVL function
- 6 Rename case when column
- 7 Use case when and grouping function together
- 8 Use case when clause to decode value
- 9 Use case when statement to replace if statement
- 10 Use case when statement with between ... and
- 11 Use case when statement with exists and subquery
- 12 Use case when statement with in()
- 13 Use case when statement with to_char() like
- 14 use case when to control the order index
- 15 Use case ... when to output comments for marks
- 16 Use case when with comparasion operator
- 17 Use the CASE expression and SUM function
- 18 Use the CASE expression and SUM function to create an order price report
- 19 You could use the case statement in an SQL statement
A searched CASE statement
SQL> BEGIN
2 CASE TRUE
3 WHEN (1 > 3) THEN
4 dbms_output.put_line("One is greater than three.");
5 WHEN (3 < 5) THEN
6 dbms_output.put_line("Three is less than five.");
7 WHEN (1 = 2) THEN
8 dbms_output.put_line("One equals two.");
9 ELSE
10 dbms_output.put_line("Nothing worked.");
11 END CASE;
12 END;
13 /
Three is less than five.
PL/SQL procedure successfully completed.
SQL>
case switch based on clob data
SQL> declare
2
3 c1 clob := to_clob("abc");
4 c2 clob;
5
6 begin
7 case c1
8 when to_clob("abc") then dbms_output.put_line("abc");
9 when to_clob("def") then dbms_output.put_line("def");
10 end case;
11
12 c2 := case c1
13 when to_clob("abc") then "abc"
14 when to_clob("def") then "def"
15 end;
16
17 dbms_output.put_line(c2);
18
19 end;
20 /
abc
abc
PL/SQL procedure successfully completed.
SQL>
case when count(*) NOT between ... and
SQL>
SQL> CREATE TABLE EMP(
2 EMPNO NUMBER(4) NOT NULL,
3 ENAME VARCHAR2(10),
4 JOB VARCHAR2(9),
5 MGR NUMBER(4),
6 HIREDATE DATE,
7 SAL NUMBER(7, 2),
8 COMM NUMBER(7, 2),
9 DEPTNO NUMBER(2)
10 );
SQL>
SQL> INSERT INTO EMP VALUES(7369, "SMITH", "CLERK", 7902,TO_DATE("17-DEC-1980", "DD-MON-YYYY"), 800, NULL, 20);
SQL> INSERT INTO EMP VALUES(7499, "ALLEN", "SALESMAN", 7698,TO_DATE("20-FEB-1981", "DD-MON-YYYY"), 1600, 300, 30);
SQL> INSERT INTO EMP VALUES(7521, "WARD", "SALESMAN", 7698,TO_DATE("22-FEB-1981", "DD-MON-YYYY"), 1250, 500, 30);
SQL> INSERT INTO EMP VALUES(7566, "JONES", "MANAGER", 7839,TO_DATE("2-APR-1981", "DD-MON-YYYY"), 2975, NULL, 20);
SQL> INSERT INTO EMP VALUES(7654, "MARTIN", "SALESMAN", 7698,TO_DATE("28-SEP-1981", "DD-MON-YYYY"), 1250, 1400, 30);
SQL> INSERT INTO EMP VALUES(7698, "BLAKE", "MANAGER", 7839,TO_DATE("1-MAY-1981", "DD-MON-YYYY"), 2850, NULL, 30);
SQL> INSERT INTO EMP VALUES(7782, "CLARK", "MANAGER", 7839,TO_DATE("9-JUN-1981", "DD-MON-YYYY"), 2450, NULL, 10);
SQL> INSERT INTO EMP VALUES(7788, "SCOTT", "ANALYST", 7566,TO_DATE("09-DEC-1982", "DD-MON-YYYY"), 3000, NULL, 20);
SQL> INSERT INTO EMP VALUES(7839, "KING", "PRESIDENT", NULL,TO_DATE("17-NOV-1981", "DD-MON-YYYY"), 5000, NULL, 10);
SQL> INSERT INTO EMP VALUES(7844, "TURNER", "SALESMAN", 7698,TO_DATE("8-SEP-1981", "DD-MON-YYYY"), 1500, 0, 30);
SQL> INSERT INTO EMP VALUES(7876, "ADAMS", "CLERK", 7788,TO_DATE("12-JAN-1983", "DD-MON-YYYY"), 1100, NULL, 20);
SQL> INSERT INTO EMP VALUES(7900, "JAMES", "CLERK", 7698,TO_DATE("3-DEC-1981", "DD-MON-YYYY"), 950, NULL, 30);
SQL> INSERT INTO EMP VALUES(7902, "FORD", "ANALYST", 7566,TO_DATE("3-DEC-1981", "DD-MON-YYYY"), 3000, NULL, 20);
SQL> INSERT INTO EMP VALUES(7934, "MILLER", "CLERK", 7782,TO_DATE("23-JAN-1982", "DD-MON-YYYY"), 1300, NULL, 10);
SQL>
SQL>
SQL> select deptno, count(*),
2 case when count(*) NOT between 3 and 8 then "..."
3 else null
4 end
5 from emp
6 group by deptno
7 /
DEPTNO COUNT(*) CAS
---------- ---------- ---
10 3
20 5
30 6
SQL> delete from emp where empno in ( 7369, 7566, 7788 );
SQL>
SQL> select deptno, count(*),
2 case when count(*) NOT between 3 and 8 then "..."
3 else null
4 end
5 from emp
6 group by deptno
7 /
DEPTNO COUNT(*) CAS
---------- ---------- ---
10 3
20 2 ...
30 6
SQL>
SQL>
SQL> drop table emp;
Combine Case with group by
SQL> -- create demo table
SQL> create table Employee(
2 empno Number(3) NOT NULL, -- Employee ID
3 ename VARCHAR2(10 BYTE), -- Employee Name
4 hireDate DATE, -- Date Employee Hired
5 orig_salary Number(8,2), -- Orignal Salary
6 curr_salary Number(8,2), -- Current Salary
7 region VARCHAR2(1 BYTE) -- Region where employeed
8 )
9 /
Table created.
SQL>
SQL> create table job(
2 empno Number(3) NOT NULL, -- Employee ID
3 jobtitle VARCHAR2(10 BYTE) -- Employee job title
4 )
5 /
SQL> -- prepare data for employee table
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(122,"Alison",to_date("19960321","YYYYMMDD"), 45000, 48000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(123, "James",to_date("19781212","YYYYMMDD"), 23000, 32000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(104,"Celia",to_date("19821024","YYYYMMDD"), 53000, 58000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(105,"Robert",to_date("19840115","YYYYMMDD"), 31000, 36000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(116,"Linda", to_date("19870730","YYYYMMDD"), 43000, 53000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(117,"David", to_date("19901231","YYYYMMDD"), 78000, 85000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(108,"Jode", to_date("19960917","YYYYMMDD"), 21000, 29000, "E")
3 /
1 row created.
SQL>
SQL>
SQL> select * from employee;
EMPNO ENAME HIREDATE ORIG_SALARY CURR_SALARY R
---------- ---------- --------- ----------- ----------- -
122 Alison 21-MAR-96 45000 48000 E
123 James 12-DEC-78 23000 32000 W
104 Celia 24-OCT-82 53000 58000 E
105 Robert 15-JAN-84 31000 36000 W
116 Linda 30-JUL-87 43000 53000 E
117 David 31-DEC-90 78000 85000 W
108 Jode 17-SEP-96 21000 29000 E
7 rows selected.
SQL>
SQL> SELECT count(*),
2 CASE region
3 WHEN "N" then "North"
4 WHEN "W" then "West"
5 WHEN null then "Null"
6 END Region -- CASE
7 FROM employee
8 GROUP BY region;
COUNT(*) REGIO
---------- -----
3 West
4
SQL>
SQL> -- clean the table
SQL> drop table Employee
2 /
Table dropped.
SQL>
SQL>
Combine case with NVL function
SQL> -- create demo table
SQL> create table Employee(
2 empno Number(3) NOT NULL, -- Employee ID
3 ename VARCHAR2(10 BYTE), -- Employee Name
4 hireDate DATE, -- Date Employee Hired
5 orig_salary Number(8,2), -- Orignal Salary
6 curr_salary Number(8,2), -- Current Salary
7 region VARCHAR2(1 BYTE) -- Region where employeed
8 )
9 /
Table created.
SQL>
SQL> create table job(
2 empno Number(3) NOT NULL, -- Employee ID
3 jobtitle VARCHAR2(10 BYTE) -- Employee job title
4 )
5 /
SQL> -- prepare data for employee table
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(122,"Alison",to_date("19960321","YYYYMMDD"), 45000, 48000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(123, "James",to_date("19781212","YYYYMMDD"), 23000, 32000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(104,"Celia",to_date("19821024","YYYYMMDD"), 53000, 58000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(105,"Robert",to_date("19840115","YYYYMMDD"), 31000, 36000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(116,"Linda", to_date("19870730","YYYYMMDD"), 43000, 53000, "E")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(117,"David", to_date("19901231","YYYYMMDD"), 78000, 85000, "W")
3 /
1 row created.
SQL> insert into Employee(empno, ename, hireDate, orig_salary, curr_salary, region)
2 values(108,"Jode", to_date("19960917","YYYYMMDD"), 21000, 29000, "E")
3 /
1 row created.
SQL>
SQL> select * from employee;
EMPNO ENAME HIREDATE ORIG_SALARY CURR_SALARY R
---------- ---------- --------- ----------- ----------- -
122 Alison 21-MAR-96 45000 48000 E
123 James 12-DEC-78 23000 32000 W
104 Celia 24-OCT-82 53000 58000 E
105 Robert 15-JAN-84 31000 36000 W
116 Linda 30-JUL-87 43000 53000 E
117 David 31-DEC-90 78000 85000 W
108 Jode 17-SEP-96 21000 29000 E
7 rows selected.
SQL>
SQL> SELECT count(*),
2 CASE NVL(region,"x")
3 WHEN "x" then "Null"
4 ELSE region
5 END Region -- CASE
6 FROM employee
7 GROUP BY region;
COUNT(*) REGI
---------- ----
3 W
4 E
SQL>
SQL> -- clean the table
SQL> drop table Employee
2 /
Table dropped.
SQL>
SQL>
SQL>
Rename case when column
SQL>
SQL> create table emp
2 ( empno NUMBER(4) constraint E_PK primary key
3 , ename VARCHAR2(8)
4 , init VARCHAR2(5)
5 , job VARCHAR2(8)
6 , mgr NUMBER(4)
7 , bdate DATE
8 , sal NUMBER(6,2)
9 , comm NUMBER(6,2)
10 , deptno NUMBER(2) default 10
11 ) ;
Table created.
SQL> insert into emp values(1,"Tom","N", "Coder", 13,date "1965-12-17", 800 , NULL, 20);
1 row created.
SQL> insert into emp values(2,"Jack","JAM", "Tester",6,date "1961-02-20", 1600, 300, 30);
1 row created.
SQL> insert into emp values(3,"Wil","TF", "Tester",6,date "1962-02-22", 1250, 500, 30);
1 row created.
SQL> insert into emp values(4,"Jane","JM", "Designer", 9,date "1967-04-02", 2975, NULL, 20);
1 row created.
SQL> insert into emp values(5,"Mary","P", "Tester",6,date "1956-09-28", 1250, 1400, 30);
1 row created.
SQL> insert into emp values(6,"Black","R", "Designer", 9,date "1963-11-01", 2850, NULL, 30);
1 row created.
SQL>
SQL> select ename, job
2 , case when job = "Coder" then " 10%"
3 when job = "Designer" then " 20%"
4 when ename = "Tom" then " 30%"
5 else " 0%"
6 end as raise
7 from emp
8 order by raise desc, ename;
ENAME JOB RAISE
-------- -------- -----
Black Designer 20%
Jane Designer 20%
Tom Coder 10%
Jack Tester 0%
Mary Tester 0%
Wil Tester 0%
6 rows selected.
SQL>
SQL>
SQL> drop table emp;
Table dropped.
Use case when and grouping function together
SQL>
SQL> create table emp
2 ( empno NUMBER(4) constraint E_PK primary key
3 , ename VARCHAR2(8)
4 , init VARCHAR2(5)
5 , job VARCHAR2(8)
6 , mgr NUMBER(4)
7 , bdate DATE
8 , sal NUMBER(6,2)
9 , comm NUMBER(6,2)
10 , deptno NUMBER(2) default 10
11 ) ;
Table created.
SQL> insert into emp values(1,"Tom","N", "TRAINER", 13,date "1965-12-17", 800 , NULL, 20);
1 row created.
SQL> insert into emp values(2,"Jack","JAM", "Tester",6,date "1961-02-20", 1600, 300, 30);
1 row created.
SQL> insert into emp values(3,"Wil","TF" , "Tester",6,date "1962-02-22", 1250, 500, 30);
1 row created.
SQL> insert into emp values(4,"Jane","JM", "Designer", 9,date "1967-04-02", 2975, NULL, 20);
1 row created.
SQL> insert into emp values(5,"Mary","P", "Tester",6,date "1956-09-28", 1250, 1400, 30);
1 row created.
SQL> insert into emp values(6,"Black","R", "Designer", 9,date "1963-11-01", 2850, NULL, 30);
1 row created.
SQL> insert into emp values(7,"Chris","AB", "Designer", 9,date "1965-06-09", 2450, NULL, 10);
1 row created.
SQL> insert into emp values(8,"Smart","SCJ", "TRAINER", 4,date "1959-11-26", 3000, NULL, 20);
1 row created.
SQL> insert into emp values(9,"Peter","CC", "Designer",NULL,date "1952-11-17", 5000, NULL, 10);
1 row created.
SQL> insert into emp values(10,"Take","JJ", "Tester",6,date "1968-09-28", 1500, 0, 30);
1 row created.
SQL> insert into emp values(11,"Ana","AA", "TRAINER", 8,date "1966-12-30", 1100, NULL, 20);
1 row created.
SQL> insert into emp values(12,"Jane","R", "Manager", 6,date "1969-12-03", 800 , NULL, 30);
1 row created.
SQL> insert into emp values(13,"Fake","MG", "TRAINER", 4,date "1959-02-13", 3000, NULL, 20);
1 row created.
SQL> insert into emp values(14,"Mike","TJA","Manager", 7,date "1962-01-23", 1300, NULL, 10);
1 row created.
SQL>
SQL> select deptno
2 , case grouping(job)
3 when 0 then job
4 when 1 then "total"
5 end job
6 , count(empno) headcount
7 from emp
8 group by ROLLUP(deptno, job);
DEPTNO JOB HEADCOUNT
---------- -------- ----------
10 Manager 1
10 Designer 2
10 total 3
20 TRAINER 4
20 Designer 1
20 total 5
30 Tester 4
30 Manager 1
30 Designer 1
30 total 6
total 14
11 rows selected.
SQL>
SQL>
SQL> drop table emp;
Table dropped.
SQL>
Use case when clause to decode value
SQL> create table registrations
2 ( attendee NUMBER(4)
3 , course VARCHAR2(6)
4 , begindate DATE
5 , evaluation NUMBER(1)
6 , constraint R_PK primary key (attendee,course,begindate)
7 ) ;
Table created.
SQL>
SQL> insert into registrations values (2,"SQL",date "2009-04-12",4 );
1 row created.
SQL> insert into registrations values (14,"SQL",date "2009-04-12",5 );
1 row created.
SQL> insert into registrations values (6,"SQL",date "2009-04-12",4 );
1 row created.
SQL> insert into registrations values (11,"SQL",date "2009-04-12",2 );
1 row created.
SQL> insert into registrations values (8,"SQL",date "2009-10-04",NULL);
1 row created.
SQL> insert into registrations values (9,"SQL",date "2009-10-04",3 );
1 row created.
SQL> insert into registrations values (13,"SQL",date "2009-10-04",4 );
1 row created.
SQL> insert into registrations values (13,"SQL",date "2009-12-13",NULL);
1 row created.
SQL> insert into registrations values (6,"SQL",date "2009-12-13",NULL);
1 row created.
SQL> insert into registrations values (3,"OAU",date "2009-08-10",4 );
1 row created.
SQL> insert into registrations values (12,"OAU",date "2009-08-10",4 );
1 row created.
SQL> insert into registrations values (13,"OAU",date "2009-08-10",5 );
1 row created.
SQL>
SQL> select attendee, begindate
2 , case evaluation
3 when 1 then "bad"
4 when 2 then "mediocre"
5 when 3 then "ok"
6 when 4 then "good"
7 when 5 then "excellent"
8 else "not filled in"
9 end
10 from registrations
11 where course = "SQL";
ATTENDEE BEGINDATE CASEEVALUATIO
---------- ---------- -------------
2 12-04-2009 good
14 12-04-2009 excellent
6 12-04-2009 good
11 12-04-2009 mediocre
8 04-10-2009 not filled in
9 04-10-2009 ok
13 04-10-2009 good
13 13-12-2009 not filled in
6 13-12-2009 not filled in
9 rows selected.
SQL>
SQL>
SQL> drop table registrations;
Table dropped.
Use case when statement to replace if statement
SQL>
SQL> create or replace procedure searched_case(p1 in number) is
2 v_switch char(1);
3 BEGIN
4 v_switch :=
5 CASE
6 WHEN p1 = 1 THEN "A"
7 WHEN p1 = 2 THEN "B"
8 WHEN p1 = 3 THEN "C"
9 END;
10 dbms_output.put_line(v_switch);
11 END;
12 /
Procedure created.
SQL>
SQL>
Use case when statement with between ... and
SQL>
SQL> create table emp(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,shortZipCode varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(5,2)
14 ,birthdate date
15 ,startDate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL>
SQL>
SQL>
SQL>
SQL> -- emp Table Inserts:
SQL> insert into emp(emp_no, lastname, firstname, midinit, street, city, state, zip,shortZipCode, area_code, phone, birthdate, title)values
2 (1,"Z","Joy","R","1 Ave","New York","NY","12122","2333","212","200-1111","12-nov-1976","President");
1 row created.
SQL>
SQL>
SQL>
SQL>
SQL> create table avg_sal
2 as select avg(salary) AS avg_Sal from emp;
Table created.
SQL>
SQL>
SQL> select
2 case when salary between 6 and 8 then "6-8"
3 when salary in (9,10) then "9-10"
4 when exists (select null from avg_sal where avg_sal = salary)
5 then "EXISTS"
6 when to_char(salary) like "2%" then "Like2"
7 when salary is null then "Null"
8 else "ELSE Empno: "|| emp_no
9 end
10 AS case_test
11 from emp
12 /
CASE_TEST
----------------------------------------------------
Null
SQL>
SQL>
SQL> drop table avg_sal;
Table dropped.
SQL>
SQL> drop table emp;
Table dropped.
SQL>
SQL>
SQL>
Use case when statement with exists and subquery
SQL>
SQL> create table emp(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,shortZipCode varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(5,2)
14 ,birthdate date
15 ,startDate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL>
SQL>
SQL>
SQL>
SQL> -- emp Table Inserts:
SQL> insert into emp(emp_no, lastname, firstname, midinit, street, city, state, zip,shortZipCode, area_code, phone, birthdate, title)values
2 (1,"Z","Joy","R","1 Ave","New York","NY","12122","2333","212","200-1111","12-nov-1976","President");
1 row created.
SQL>
SQL>
SQL>
SQL>
SQL> create table avg_sal
2 as select avg(salary) AS avg_Sal from emp;
Table created.
SQL>
SQL>
SQL> select
2 case when salary between 6 and 8 then "6-8"
3 when salary in (9,10) then "9-10"
4 when exists (select null from avg_sal where avg_sal = salary)
5 then "EXISTS"
6 when to_char(salary) like "2%" then "Like2"
7 when salary is null then "Null"
8 else "ELSE Empno: "|| emp_no
9 end
10 AS case_test
11 from emp
12 /
CASE_TEST
----------------------------------------------------
Null
SQL>
SQL>
SQL> drop table avg_sal;
Table dropped.
SQL>
SQL> drop table emp;
Table dropped.
SQL>
SQL>
SQL>
Use case when statement with in()
SQL>
SQL> create table emp(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,shortZipCode varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(5,2)
14 ,birthdate date
15 ,startDate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL>
SQL>
SQL>
SQL>
SQL> -- emp Table Inserts:
SQL> insert into emp(emp_no, lastname, firstname, midinit, street, city, state, zip,shortZipCode, area_code, phone, birthdate, title)values
2 (1,"Z","Joy","R","1 Ave","New York","NY","12122","2333","212","200-1111","12-nov-1976","President");
1 row created.
SQL>
SQL>
SQL>
SQL>
SQL> create table avg_sal
2 as select avg(salary) AS avg_Sal from emp;
Table created.
SQL>
SQL>
SQL> select
2 case when salary between 6 and 8 then "6-8"
3 when salary in (9,10) then "9-10"
4 when exists (select null from avg_sal where avg_sal = salary)
5 then "EXISTS"
6 when to_char(salary) like "2%" then "Like2"
7 when salary is null then "Null"
8 else "ELSE Empno: "|| emp_no
9 end
10 AS case_test
11 from emp
12 /
CASE_TEST
----------------------------------------------------
Null
SQL>
SQL>
SQL> drop table avg_sal;
Table dropped.
SQL>
SQL> drop table emp;
Table dropped.
SQL>
SQL>
SQL>
Use case when statement with to_char() like
SQL>
SQL> create table emp(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,shortZipCode varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(5,2)
14 ,birthdate date
15 ,startDate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL>
SQL>
SQL>
SQL>
SQL> -- emp Table Inserts:
SQL> insert into emp(emp_no, lastname, firstname, midinit, street, city, state, zip,shortZipCode, area_code, phone, birthdate, title)values
2 (1,"Z","Joy","R","1 Ave","New York","NY","12122","2333","212","200-1111","12-nov-1976","President");
1 row created.
SQL>
SQL>
SQL>
SQL>
SQL> create table avg_sal
2 as select avg(salary) AS avg_Sal from emp;
Table created.
SQL>
SQL>
SQL> select
2 case when salary between 6 and 8 then "6-8"
3 when salary in (9,10) then "9-10"
4 when exists (select null from avg_sal where avg_sal = salary)
5 then "EXISTS"
6 when to_char(salary) like "2%" then "Like2"
7 when salary is null then "Null"
8 else "ELSE Empno: "|| emp_no
9 end
10 AS case_test
11 from emp
12 /
CASE_TEST
----------------------------------------------------
Null
SQL>
SQL>
SQL> drop table avg_sal;
Table dropped.
SQL>
SQL> drop table emp;
Table dropped.
SQL>
SQL>
SQL>
use case when to control the order index
SQL>
SQL>
SQL> create table emp
2 ( empno NUMBER(4) constraint E_PK primary key
3 , ename VARCHAR2(8)
4 , init VARCHAR2(5)
5 , job VARCHAR2(8)
6 , mgr NUMBER(4)
7 , bdate DATE
8 , sal NUMBER(6,2)
9 , comm NUMBER(6,2)
10 , deptno NUMBER(2) default 10
11 ) ;
Table created.
SQL> insert into emp values(1,"Tom","N", "TRAINER", 13,date "1965-12-17", 800 , NULL, 20);
1 row created.
SQL> insert into emp values(2,"Jack","JAM", "Tester",6,date "1961-02-20", 1600, 300, 30);
1 row created.
SQL> insert into emp values(3,"Wil","TF" , "Tester",6,date "1962-02-22", 1250, 500, 30);
1 row created.
SQL> insert into emp values(4,"Jane","JM", "Designer", 9,date "1967-04-02", 2975, NULL, 20);
1 row created.
SQL> insert into emp values(5,"Mary","P", "Tester",6,date "1956-09-28", 1250, 1400, 30);
1 row created.
SQL> insert into emp values(6,"Black","R", "Designer", 9,date "1963-11-01", 2850, NULL, 30);
1 row created.
SQL> insert into emp values(7,"Chris","AB", "Designer", 9,date "1965-06-09", 2450, NULL, 10);
1 row created.
SQL> insert into emp values(8,"Smart","SCJ", "TRAINER", 4,date "1959-11-26", 3000, NULL, 20);
1 row created.
SQL> insert into emp values(9,"Peter","CC", "Designer",NULL,date "1952-11-17", 5000, NULL, 10);
1 row created.
SQL> insert into emp values(10,"Take","JJ", "Tester",6,date "1968-09-28", 1500, 0, 30);
1 row created.
SQL> insert into emp values(11,"Ana","AA", "TRAINER", 8,date "1966-12-30", 1100, NULL, 20);
1 row created.
SQL> insert into emp values(12,"Jane","R", "Manager", 6,date "1969-12-03", 800 , NULL, 30);
1 row created.
SQL> insert into emp values(13,"Fake","MG", "TRAINER", 4,date "1959-02-13", 3000, NULL, 20);
1 row created.
SQL> insert into emp values(14,"Mike","TJA","Manager", 7,date "1962-01-23", 1300, NULL, 10);
1 row created.
SQL> select job, ename
2 , case
3 when sal <= 2500
4 then "cheap"
5 else "expensive"
6 end as class
7 from emp
8 where bdate < date "1964-01-01"
9 order by case job
10 when "Designer" then 1
11 when "Designer" then 2
12 else 3
13 end;
Enter...
Designer Black expensive
Designer Peter expensive
Tester Mary cheap
Manager Mike cheap
TRAINER Smart expensive
TRAINER Fake expensive
Tester Wil cheap
Tester Jack cheap
8 rows selected.
SQL>
SQL> drop table emp;
Table dropped.
SQL>
Use case ... when to output comments for marks
SQL>
SQL>
SQL> CREATE TABLE empExam (
2 empID INT NOT NULL,
3 ExamID INT NOT NULL,
4 Mark INT,
5 Taken SMALLINT,
6 Comments VARCHAR(255),
7 CONSTRAINT PK_empExam PRIMARY KEY (empID, ExamID));
Table created.
SQL>
SQL>
SQL> INSERT INTO empExam (empID,ExamID,Mark,Taken,Comments) VALUES (1,1,55,1,"Satisfactory");
1 row created.
SQL> INSERT INTO empExam (empID,ExamID,Mark,Taken,Comments) VALUES (1,2,73,1,"Good result");
1 row created.
SQL> INSERT INTO empExam (empID,ExamID,Mark,Taken,Comments) VALUES (2,3,44,1,"Hard");
1 row created.
SQL> INSERT INTO empExam (empID,ExamID,Mark,Taken,Comments) VALUES (2,5,39,0,"Simple");
1 row created.
SQL> INSERT INTO empExam (empID,ExamID,Mark,Taken) VALUES (2,6,63,1);
1 row created.
SQL>
SQL> CREATE OR REPLACE PROCEDURE GetempComments(i_empID IN INT,o_Comments OUT VARCHAR)
2 AS
3 exams_sat INT;
4 avg_mark INT;
5 tmp_comments VARCHAR(100);
6 BEGIN
7 SELECT COUNT(ExamID) INTO exams_sat FROM empExam
8 WHERE empID = i_empID;
9 IF exams_sat = 0 THEN
10 tmp_comments := "n/a - this emp sat no exams";
11 ELSE
12 SELECT AVG(Mark) INTO avg_mark FROM empExam
13 WHERE empID = i_empID;
14 CASE
15 WHEN avg_mark < 50 THEN tmp_comments := "Poor";
16 WHEN avg_mark < 60 THEN tmp_comments := "Adequate.";
17 WHEN avg_mark < 70 THEN tmp_comments := "Satisfactory.";
18 ELSE tmp_comments := "Excellent!";
19 END CASE;
20 END IF;
21 o_Comments := tmp_comments;
22 END;
23 /
SP2-0804: Procedure created with compilation warnings
SQL> SET SERVEROUT ON
SQL> DECLARE
2 comments VARCHAR(100);
3 BEGIN
4 GetempComments(2, comments);
5 dbms_output.put_line(comments);
6 END;
7 /
Poor
PL/SQL procedure successfully completed.
SQL>
SQL>
SQL> drop table empExam;
Table dropped.
Use case when with comparasion operator
SQL>
SQL> create table emp(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,shortZipCode varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(5,2)
14 ,birthdate date
15 ,startDate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL>
SQL>
SQL>
SQL>
SQL>
SQL> create table avg_sal
2 as select avg(salary) AS avg_Sal from emp;
Table created.
SQL>
SQL> select lastname, salary,
2 CASE WHEN salary > avg_sal THEN "> Average of " || to_char(avg_sal, "99.99")
3 WHEN salary < avg_sal THEN "< Average of " || to_char(avg_sal, "99.99")
4 ELSE "= Average of " || to_char(avg_sal, "99.99")
5 END
6 from emp, avg_sal
7 /
no rows selected
SQL>
SQL> drop table emp;
Table dropped.
SQL>
SQL>
SQL>
SQL>
SQL> drop table avg_Sal;
Table dropped.
SQL>
Use the CASE expression and SUM function
SQL>
SQL>
SQL> create table employee(
2 emp_no integer primary key
3 ,lastname varchar2(20) not null
4 ,firstname varchar2(15) not null
5 ,midinit varchar2(1)
6 ,street varchar2(30)
7 ,city varchar2(20)
8 ,state varchar2(2)
9 ,zip varchar2(5)
10 ,zip_4 varchar2(4)
11 ,area_code varchar2(3)
12 ,phone varchar2(8)
13 ,salary number(3)
14 ,birthdate date
15 ,hiredate date
16 ,title varchar2(20)
17 ,dept_no integer
18 ,mgr integer
19 ,region number
20 ,division number
21 ,total_sales number
22 );
Table created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (1,"Anderson","Nancy","N","33 Ave","London","NY","11111","1111","212","234-1111",3.75,"21-mar-1927","1-feb-1947","Sales Manager",2,null,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (2,"Last","First","F","12 Ave","Paris","CA","22222","2222","223","867-2222",7.75,"14-feb-1976","15-mar-1985","Sales Clerk",2,1,100,10,10000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (3,"Wash","Georgia","G","1 Street14","Barton","NJ","33333","3333","214","340-3333",11.50,"2-jul-1977","21-apr-2004","Designer",1,2,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (4,"Bush","Dave","D","56 Street","Island","RI","44444","4444","215","777-4444",21.65,"15-may-1945","2-aug-1975","Designer",1,2,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (5,"Will","Robin","W","56 Street","Island","MA","55555","5555","216","777-5555",24.65,"10-dec-1980","2-aug-2007","Designer",1,5,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (6,"Pete","Mona","M","13 Ave","York","MO","66666","6666","217","111-6666",9,"14-feb-1966","15-mar-1985","Sales Clerk",2,5,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (7,"Roke","John","J","67 Ave","New York","BC","77777","7777","218","122-7777",10.00,"14-jun-1955","15-mar-1975","Accountant",3,2,100,10,40000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (8,"Horry","Tedi","T","1236 Lane","Newton","NY","88888","8888","219","222-8888",13.00,"10-jun-1955","15-aug-1985","Sales Representative",3,2,100,10,50000);
1 row created.
SQL> insert into employee(emp_no, lastname, firstname, midinit, street, city, state, zip,zip_4, area_code, phone, salary, birthdate, hiredate,title, dept_no, mgr, region, division, total_sales)
2 values (9,"Bar","Candi","C","400 East Street","Yorken","NY","99999","9999","220","321-9999",12.00,"10-oct-1933","15-jan-1969","Sales Representative",3,5,100,10,35000);
1 row created.
SQL>
SQL> select * from employee;
EMP_NO LASTNAME FIRSTNAME M STREET CITY ST ZIP ZIP_ ARE PHONE SALARY
---------- -------------------- --------------- - ------------------------------ -------------------- -- ----- ---- --- -------- ----------
BIRTHDATE HIREDATE TITLE DEPT_NO MGR REGION DIVISION TOTAL_SALES
-------------------- -------------------- -------------------- ---------- ---------- ---------- ---------- -----------
1 Anderson Nancy N 33 Ave London NY 11111 1111 212 234-1111 4
21-MAR-1927 00:00:00 01-FEB-1947 00:00:00 Sales Manager 2 100 10 40000
2 Last First F 12 Ave Paris CA 22222 2222 223 867-2222 8
14-FEB-1976 00:00:00 15-MAR-1985 00:00:00 Sales Clerk 2 1 100 10 10000
3 Wash Georgia G 1 Street14 Barton NJ 33333 3333 214 340-3333 12
02-JUL-1977 00:00:00 21-APR-2004 00:00:00 Designer 1 2 100 10 40000
4 Bush Dave D 56 Street Island RI 44444 4444 215 777-4444 22
15-MAY-1945 00:00:00 02-AUG-1975 00:00:00 Designer 1 2 100 10 40000
5 Will Robin W 56 Street Island MA 55555 5555 216 777-5555 25
10-DEC-1980 00:00:00 02-AUG-2007 00:00:00 Designer 1 5 100 10 40000
6 Pete Mona M 13 Ave York MO 66666 6666 217 111-6666 9
14-FEB-1966 00:00:00 15-MAR-1985 00:00:00 Sales Clerk 2 5 100 10 40000
7 Roke John J 67 Ave New York BC 77777 7777 218 122-7777 10
14-JUN-1955 00:00:00 15-MAR-1975 00:00:00 Accountant 3 2 100 10 40000
8 Horry Tedi T 1236 Lane Newton NY 88888 8888 219 222-8888 13
10-JUN-1955 00:00:00 15-AUG-1985 00:00:00 Sales Representative 3 2 100 10 50000
9 Bar Candi C 400 East Street Yorken NY 99999 9999 220 321-9999 12
10-OCT-1933 00:00:00 15-JAN-1969 00:00:00 Sales Representative 3 5 100 10 35000
9 rows selected.
SQL>
SQL> select dept_no, title,
2 case
3 when upper(title) like "%SALES%" then sum(salary)
4 when upper(title) = "ACCOUNTANT" then sum(salary)
5 when upper(title) = "DESIGNER" then sum(salary)
6 end AS sum_salary
7 FROM EMPLOYEE
8 GROUP BY dept_no, title;
DEPT_NO TITLE SUM_SALARY
---------- -------------------- ----------
2 Sales Clerk 17
1 Designer 59
3 Sales Representative 25
2 Sales Manager 4
3 Accountant 10
5 rows selected.
SQL>
SQL>
SQL> drop table employee;
Table dropped.
SQL> --
Use the CASE expression and SUM function to create an order price report
SQL>
SQL>
SQL> create table ord(
2 order_no integer primary key
3 ,cust_no integer
4 ,order_date date not null
5 ,total_order_price number(7,2)
6 ,deliver_date date
7 ,deliver_time varchar2(7)
8 ,payment_method varchar2(2)
9 ,emp_no number(3,0)
10 ,deliver_name varchar2(35)
11 ,gift_message varchar2(100)
12 );
Table created.
SQL>
SQL>
SQL> insert into ord(order_no,cust_no,order_date,total_order_price,deliver_date,deliver_time,payment_method,emp_no,deliver_name,gift_message)
2 values(1,1,"14-Feb-2002", 23.00, "14-Feb-2002", "12 noon", "CA",1, null, "Gift for wife");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time ,payment_method ,emp_no,deliver_name ,gift_message )
2 values(2,1,"14-Feb-2003", 510.98, "14-feb-2003", "5 pm", "NY",7, "Rose Ted", "Happy Valentines Day to Mother");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(3, 2,"14-Feb-2004", 315.99, "14-feb-2004", "3 pm", "VS",2, "Ani Forest", "Happy Valentines Day to Father");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(4, 2,"14-Feb-1999", 191.95, "14-feb-1999", "2 pm", "NJ",2, "O. John", "Happy Valentines Day");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(5, 6,"4-mar-2002", 101.95, "5-mar-2002", "2:30 pm", "MO" , 2, "Cora", "Happy Birthday from John");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(6, 9,"7-apr-2003", 221.95, "7-apr-2003", "3 pm", "MA", 2, "Sake Keith", "Happy Birthday from Joe" );
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(7, 9,"20-jun-2004", 315.95, "21-jun-2004", "12 noon", "BC", 2, "Jessica Li", "Happy Birthday from Jessica");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values (8, 12, "31-dec-1999", 135.95, "1-jan-2000", "12 noon", "DI", 3, "Larry", "Happy New Year from Lawrence");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values (9, 12, "26-dec-2003", 715.95, "2-jan-2004", "12 noon", "SK",7, "Did", "Happy Birthday from Nancy" );
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(10, 4, sysdate-1, 119.95, sysdate+2, "6:30 pm", "VG",2, "P. Jing", "Happy Valentines Day to Jason");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message )
2 values(11, 2, sysdate, 310.00, sysdate+2, "3:30 pm", "DC",2, "C. Late", "Happy Birthday Day to Jack");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message)
2 values(12, 7, sysdate-3, 121.95, sysdate-2, "1:30 pm", "AC",2, "W. Last", "Happy Birthday Day to You");
1 row created.
SQL> insert into ord(order_no ,cust_no ,order_date ,total_order_price ,deliver_date ,deliver_time,payment_method ,emp_no,deliver_name ,gift_message)
2 values(13, 7, sysdate, 211.95, sysdate-4, "4:30 pm", "CA",2, "J. Bond", "Thanks for hard working");
1 row created.
SQL>
SQL> select payment_method from ord;
PA
--
CA
NY
VS
NJ
MO
MA
BC
DI
SK
VG
DC
AC
CA
13 rows selected.
SQL>
SQL> select case payment_method when "CA" then "CASH"
2 when "DI" then "DISCOVER"
3 when "VG" then "VISA GOLD"
4 when "VS" then "VISA STANDARD"
5 when "AX" then "AMEX"
6 ELSE "OTHER"
7 END AS pay_method,
8 sum( case when total_order_price < 30 then 1 else 0 end) AS Small_Order,
9 sum( case when total_order_price = 30 then 1 else 0 end) AS Medium_Order,
10 sum( case when total_order_price > 30 then 1 else 0 end) AS Large_Order
11 from ord
12 group by payment_method
13 /
PAY_METHOD SMALL_ORDER MEDIUM_ORDER LARGE_ORDER
------------- ----------- ------------ -----------
VISA STANDARD 0 0 1
OTHER 0 0 1
CASH 1 0 1
OTHER 0 0 1
OTHER 0 0 1
DISCOVER 0 0 1
VISA GOLD 0 0 1
OTHER 0 0 1
OTHER 0 0 1
OTHER 0 0 1
OTHER 0 0 1
OTHER 0 0 1
12 rows selected.
SQL>
SQL> drop table ord;
Table dropped.
SQL> --
You could use the case statement in an SQL statement
SQL>
SQL>
SQL> -- You could use the case statement in an SQL statement as follows:
SQL>
SQL> select table_name,
2 CASE owner
3 WHEN "SYS" THEN "The owner is SYS"
4 WHEN "SYSTEM" THEN "The owner is SYSTEM"
5 ELSE "The owner is another value" END
6 from all_tables
7 where rownum<200;
TABLE_NAME CASEOWNERWHEN"SYS"THEN"THE
------------------------------ --------------------------
CON$ The owner is SYS
RULESET$ The owner is SYS
INDPART_PARAM$ The owner is SYS
OL$ The owner is another value
OL$HINTS The owner is another value
OL$NODES The owner is another value
SQL$ The owner is SYS
SQL$TEXT The owner is SYS
SQLPROF$ The owner is SYS
SQLPROF$DESC The owner is SYS
SQL>
SQL>