Decode Case Function

Embed Size (px)

Citation preview

  • 8/12/2019 Decode Case Function

    1/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.11

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.SKILLBUILDERS

    2.2. DECODEDECODE Function,Function,CASECASE ExpressionExpression

    Introduction to DECODE

    DECODE Examples

    Contrast with 9i Case Statement

    CASE Examples

    CASE Histograms

  • 8/12/2019 Decode Case Function

    2/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.22

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.22

    Introduction toIntroduction to DECODEDECODE

    Extension to ANSI SQL

    I FTHEN. . ELSE function

    Compares value to I F values, 1 by 1

    If equal match found, returns correspondingTHENvalue

    Returns ELSE value if no match foundNULL if ELSE not specified

    DECODE( val ue, i f 1, t hen1, i f 2, t hen2, . . . [ , el se] )DECODE( val ue, i f 1, t hen1, i f 2, t hen2, . . . [ , el se] )

    DECODE is an Oracle extension that adds an IF/THEN/ELSEfunction to SQL. Thesyntax allows the specification of a limited number of IF/THEN value pairs. Oraclecompares the supplied VALUE to the IFvalues (one by one) and returns the first

    THENvalue if an equality match is found. If a match is not found, the ELSEvalueis returned, if coded. If ELSE is not coded and a match is not found, NULL is

    returned.

    Notable things about DECODE:

    VALUE, IF, THENand ELSEcan be expressions. For example, SYSDATE-BI RTHDATE. Functions can also be used. (See examples later in this section.)

    In DECODE, Oracle considers two NULLs to be equivalent.

    The maximum number of items, including VALUE, IF, THENand ELSEvaluesis 255.

  • 8/12/2019 Decode Case Function

    3/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.33

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.33

    Simple ExampleSimple Example

    Convert state abbreviations to name

    SELECT st ate, DECODE (state,

    ' NY' , ' New Yor k' ,

    ' NJ ' , ' New J ersey' ,

    ' RI ' , ' Rhode I sl and' ,

    ' Unknown' ) AS st at e_name

    FROM cust omer ;

    SELECT st ate, DECODE (state,

    ' NY' , ' New Yor k' ,

    ' NJ ' , ' New J ersey' ,

    ' RI ' , ' Rhode I sl and' ,

    ' Unknown' ) AS st at e_name

    FROM cust omer ;

    ST STATE_ NAME

    - - - - - - - - - - - - - -

    NY New Yor k

    . . .

    MO UnknownRI Rhode I sl and

    NY New Yor k

    ST STATE_ NAME

    - - - - - - - - - - - - - -

    NY New Yor k

    . . .

    MO UnknownRI Rhode I sl and

    NY New Yor k

    DECODE Function

    The example decodes state abbreviations and replaces them with state names.Note that the DECODE function has code/value pairs, followed by an optional defaultvalue to be used if the code is not found in the set of code/value pairs. NULL is

    used if there is no default specified.

    Idea: DECODE is an extremely powerful function. It can be used to perform a

    host of special manipulations such as invoice aging, flipping tables on their side,and calculating columns where the calculation itself varies by row. For example,you could calculate the new salary for all employees where the increase variesbased on the employees date of hire. These uses are beyond the scope of thiscourse. Oracle: The Complete Reference, the Oracle Press book from Osborne,has an entire chapter dedicated to the various ways that you can use DECODE.

  • 8/12/2019 Decode Case Function

    4/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.44

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.44

    Flip Table on SideFlip Table on Sidesel ect cust_no, sum( decode ( payment _method, ' CA' , t otal _order_pr i ce) ) cash, sum( decode (payment _method, ' VG' , t otal _order_pr i ce) ) vi sa_gol d, sum( decode ( payment _method, ' VS' , t otal _order_pr i ce) ) vi sa_st nd, sum( decode ( payment _method, ' DI ' , t otal _order_pr i ce) ) di scover, sum( t ot al _or der _pr i ce) t ot alf romordgroup by cust _no;

    CUST_NO CASH VI SA_GOLD VI SA_STND DI SCOVER TOTAL- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    1 50. 98 50. 982 19. 95 30 35. 99 85. 944 19. 95 19. 95

    6 10. 95 10. 957 43. 9 43. 99 133. 9 133. 9

    12 75. 95 35. 95 111. 9

    sel ect cust_no, sum( decode ( payment _method, ' CA' , t otal _order_pr i ce) ) cash, sum( decode (payment _method, ' VG' , t otal _order_pr i ce) ) vi sa_gol d, sum( decode ( payment _method, ' VS' , t otal _order_pr i ce) ) vi sa_st nd, sum( decode ( payment _method, ' DI ' , t otal _order_pr i ce) ) di scover, sum( t ot al _or der _pr i ce) t ot alf romordgroup by cust _no;

    CUST_NO CASH VI SA_GOLD VI SA_STND DI SCOVER TOTAL- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    1 50. 98 50. 982 19. 95 30 35. 99 85. 944 19. 95 19. 956 10. 95 10. 95

    7 43. 9 43. 99 133. 9 133. 9

    12 75. 95 35. 95 111. 9

    The DECODE function is often used to turn a table on its side. Or, put another way,

    turn table values into columns. The essence of doing this is to:

    DECODE the column you would like to make into columns. In this example, Ihave decoded PAYMENT_METHOD.

    Supply a relevant column for the THENvalue. In this case I have codedTOTAL_ORDER_PRICE.

    Code NULL (or take the default NULL as in this example) for the ELSEvalue.

    Supply a meaningful column alias (column name). In this example, I havesupplied cash for value CA, vi sa_gol d, VG, etc.

    In this example I have also use the aggregate function SUM to display the total

    amount spent by a customer via cash payment method. For example, customernumber 2 has spent a total of $19.95 in cash, $30 in Visa Gold and $35.99 in VisaStandard.

    See the supplied script DECODE2. SQL for a working example.

  • 8/12/2019 Decode Case Function

    5/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.55

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.55

    DECODEDECODE and Rangeand Range

    ComparisonsComparisons Use SI GN function to build less than, greater than comparisonssel ect l astname, sal ary,decode( s i gn( sal ary - avg_sal ) ,

    1, ' > Average of ' | | to_char( avg_sal , ' 99. 99' ) ,0, ' = Average of ' | | to_char( avg_sal , ' 99. 99' ) ,

    - 1, ' < Average of ' | | t o_char( avg_sal , ' 99. 99' ) ) sal _descf r omempl oyee, avg_sal ;

    LASTNAME SALARY SAL_ DESC- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Anderson 8 < Average of 13. 00Somers 8 < Average of 13. 00Washi ngt on 12 < Average of 13. 00Dori ght 22 > Aver age of 13. 00Wel l s 25 > Aver age of 13. 00

    Per r y 9 < Aver age of 13. 00Roger 10 < Average of 13. 00Hal l 13 = Aver age of 13. 00Barbee 12 < Average of 13. 00

    sel ect l astname, sal ary,decode( s i gn( sal ary - avg_sal ) ,

    1, ' > Average of ' | | to_char( avg_sal , ' 99. 99' ) ,0, ' = Average of ' | | to_char( avg_sal , ' 99. 99' ) ,

    - 1, ' < Average of ' | | t o_char( avg_sal , ' 99. 99' ) ) sal _descf r omempl oyee, avg_sal ;

    LASTNAME SALARY SAL_ DESC- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Anderson 8 < Average of 13. 00Somers 8 < Average of 13. 00Washi ngt on 12 < Average of 13. 00Dori ght 22 > Aver age of 13. 00Wel l s 25 > Aver age of 13. 00

    Per r y 9 < Aver age of 13. 00Roger 10 < Average of 13. 00Hal l 13 = Aver age of 13. 00Barbee 12 < Average of 13. 00

    We can build a range comparison into the DECODE by incorporating the SI GNfunction. SI GN returns:

    1 if the result is positive

    -1 if the result is negative

    0 if the result is 0

    This example assumes the following view has been created:

    cr eat e or r epl ace vi ew avg_Sal

    as sel ect t r unc( avg( sal ar y) ) avg_sal

    f r om empl oyee;

    To help understand this example, divide employee Andersons salary by theaverage and subtract 1: 8 - 13 = -5. The SI GN function returns 1 (since the resultis negative) and DECODE translates that into the string < Aver age of ' | |t o_char ( avg_sal , ' 99. 99' ) . Try the same for Hall: 13 - 13 = 0. Since theresult is 0, the SI GN function returns 0.

    See the supplied script DECODE3. SQL for a working example.

  • 8/12/2019 Decode Case Function

    6/13

  • 8/12/2019 Decode Case Function

    7/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.77

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.77

    CASECASE SyntaxSyntax

    Simple CASE

    Searched CASE

    CASE expressi on WHEN t hi s1 THEN t hat 1WHEN t hi s2 THEN t hat 2 . . .[ ELSE t hat ]END

    CASE expressi on WHEN t hi s1 THEN t hat 1WHEN t hi s2 THEN t hat 2 . . .[ ELSE t hat ]END

    CASE WHEN condi t i on1 THEN r et urn- val ue1WHEN condi t i on2 THEN r et urn- val ue2

    . . .[ ELSE r et ur n- val ue ]

    END

    CASE WHEN condi t i on1 THEN r et urn- val ue1WHEN condi t i on2 THEN r et urn- val ue2

    . . .[ ELSE r et ur n- val ue ]END

    Oracle supports two flavors of CASE, simple and searched.

    The simple case expression tests for an equal condition on the supplied value orexpression. The first WHEN value that is equal causes Oracle to return the

    corresponding THEN value. If none of the WHEN values match the suppliedexpression, the ELSE value is returned. If the ELSE is not coded, NULL is returned.

    The searched case (as seen in the previous example) allows multiple comparisonexpressions ( , =, BETWEEN, LI KE, I N, I S NULL, etc.). Thefirst TRUE expression causes Oracle to return the corresponding THEN value. Ifnone of the WHEN values match the supplied expression, the ELSE value isreturned. If the ELSE is not coded, NULL is returned.

  • 8/12/2019 Decode Case Function

    8/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.88

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.88

    CASECASE NonsenseNonsense

    CASE supports many comparisons

    sel ectcase when sal ary bet ween 6 and 8 t hen ' 6- 8'

    when sal ar y i n ( 9, 10) t hen ' 9- 10'when exi st s ( sel ect nul l f r om avg_sal

    wher e avg_sal = sal ar y)t hen ' EXI STS'

    when t o_char ( sal ar y) l i ke ' 2%' t hen ' Li ke2'when sal ar y i s nul l t hen ' Nul l 'when emp_no i n ( sel ect mgr _no f r omdepart ment )

    t hen ' Dpt Mgr 'el se ' ELSE'endAS case_t est

    f r omempl oyee, avg_sal

    sel ectcase when sal ary bet ween 6 and 8 t hen ' 6- 8'

    when sal ar y i n ( 9, 10) t hen ' 9- 10'when exi st s ( sel ect nul l f r om avg_sal

    wher e avg_sal = sal ar y)t hen ' EXI STS'

    when t o_char ( sal ar y) l i ke ' 2%' t hen ' Li ke2'when sal ar y i s nul l t hen ' Nul l 'when emp_no i n ( sel ect mgr _no f r omdepart ment )

    t hen ' Dpt Mgr 'el se ' ELSE'

    endAS case_t est

    f r omempl oyee, avg_sal

    This example illustrates the breadth of support for the various relational comparisonoperators supported by Oracle.

  • 8/12/2019 Decode Case Function

    9/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.99

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.99

    Histograms withHistograms with CASECASE

    Easily define number and width of buckets

    sel ectsum ( case when sal ary bet ween 6 and 10 t hen 1 el se 0 end )

    as sal _6_10,sum ( case when sal ary bet ween 11 and 15 t hen 1 el se 0 end )

    as sal _11_15,sum ( case when sal ary bet ween 16 and 20 t hen 1 el se 0 end )

    as sal _16_20,sum ( case when sal ary bet ween 21 and 25 t hen 1 el se 0 end )

    as sal _21_25f r omempl oyee;

    SAL_6_10 SAL_11_15 SAL_16_20 SAL_21_25- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -4 3 0 2

    sel ectsum ( case when sal ary bet ween 6 and 10 t hen 1 el se 0 end )

    as sal _6_10,sum ( case when sal ary bet ween 11 and 15 t hen 1 el se 0 end )

    as sal _11_15,sum ( case when sal ary bet ween 16 and 20 t hen 1 el se 0 end )

    as sal _16_20,sum ( case when sal ary bet ween 21 and 25 t hen 1 el se 0 end )

    as sal _21_25f r omempl oyee;

    SAL_6_10 SAL_11_15 SAL_16_20 SAL_21_25- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    4 3 0 2

    Histograms can be easily created with the CASE expression.

    In this example, to show the distribution of salary levels, I have created a histogramcontaining 4 buckets and each bucket has a width of 5.

  • 8/12/2019 Decode Case Function

    10/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.1010

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.1010

    Histograms withHistograms with CASECASE

    sel ectcase when sal ary bet ween 6 and 10 t hen ' Sal ary 06- 10'when sal ary bet ween 11 and 15 then ' Sal ary 11- 15'when sal ary bet ween 16 and 20 then ' Sal ary 16- 20'when sal ary bet ween 21 and 25 then ' Sal ary 21- 25'el se ' Sal ar y OOR' endAS bucket , count ( *) num_emps

    f r omempl oyeegroup bycase when sal ary bet ween 6 and 10 t hen ' Sal ary 06- 10'

    when sal ary bet ween 11 and 15 then ' Sal ary 11- 15'when sal ary bet ween 16 and 20 then ' Sal ary 16- 20'when sal ary bet ween 21 and 25 then ' Sal ary 21- 25'el se ' Sal ary OOR'

    end;

    sel ectcase when sal ary bet ween 6 and 10 t hen ' Sal ary 06- 10'

    when sal ary bet ween 11 and 15 then ' Sal ary 11- 15'when sal ary bet ween 16 and 20 then ' Sal ary 16- 20'when sal ary bet ween 21 and 25 then ' Sal ary 21- 25'el se ' Sal ar y OOR' endAS bucket , count ( *) num_emps

    f r omempl oyeegroup bycase when sal ary bet ween 6 and 10 t hen ' Sal ary 06- 10'

    when sal ary bet ween 11 and 15 then ' Sal ary 11- 15'when sal ary bet ween 16 and 20 then ' Sal ary 16- 20'when sal ary bet ween 21 and 25 then ' Sal ary 21- 25'el se ' Sal ary OOR'

    end; BUCKET NUM_EMPS- - - - - - - - - - - - - - - - - - - - - -Sal ary 06- 10 4Sal ary 11- 15 3Sal ary 21- 25 2

    BUCKET NUM_EMPS

    - - - - - - - - - - - - - - - - - - - - - -Sal ary 06- 10 4Sal ary 11- 15 3Sal ary 21- 25 2

    This example shows that the CASE expression can be used in the GROUP BY

    clause.

    Like the previous example I am showing the distribution of salary levels. However,

    in this example, each bucket in the histogram is represented by a row in the result(as opposed to a column), and empty buckets are not included in the result.

  • 8/12/2019 Decode Case Function

    11/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.1111

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2004 SkillBuilders, Inc.

    2.2.1111

    DecodeDecode andand CaseCase WorkshopWorkshop

    Using Decode and Case

    DECODE Workshop

    1. Create a report that shows number of customers per state. Use the SUMandDECODE functions to format the report similar to:

    NJ NY RI- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    2 10 1

    2. Add an "OTHER" and "TOTAL" column to the report:

    NJ NY RI OTHER TOTAL

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    2 10 1 1 14

  • 8/12/2019 Decode Case Function

    12/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.1212

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    3. Use DECODE and SI GN functions on the ORD table to create a report similar to:

    SI ZE_ORDER NUM_ORDERS

    - - - - - - - - - - - - - - - - - - - - - -

    Large Or der 5Medi umOr der 1

    Smal l order 6

    Assume that a $30 order (t ot al _or der _pr i ce) is a "Medium Order".

    Hint: You will need to repeat the DECODE function in the GROUP BY clause.

    CASE Workshop

    1. Use the CASE expression and SUMfunction (in the CASE "THEN" )to create the following report.

    The SUM_SALARY column is the sum of the salary of all employees with the same

    job title by department.

    DEPT_NO TI TLE SUM_SALARY

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    1 Desi gner 59

    2 Sal es Cl er k 172 Sal es Manager 8

    3 Accountant 10

    3 Sal es Repr esent at i ve 25

    Hint: GROUP BY dept _no, t i t l e

  • 8/12/2019 Decode Case Function

    13/13

    DECODE Function, CASE ExpressionDECODE Function, CASE Expression 2.2.1313

    2004 SkillBuilders, Inc. 2004 SkillBuilders, Inc. V 1.2V 1.2

    2. Use the CASE expression and SUMfunction to create an order price report

    similar to :

    PAY_METHOD SMALL_ORDER MEDI UM_ORDER LARGE_ORDER

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    CASH 3 0 2

    DI SCOVER 0 0 1

    VI SA GOLD 1 1 0

    VI SA STANDARD 2 0 2

    Hints: SUM the result of the CASE expressions. GROUP BY the payment _met hod

    column.