Monday, 29 October 2012

How to Write a Case Statement in SQL?

Case Statement facilitates conditional enquiries by doing  the work of  an if-then else statement
The general form of case expression usage is:

case expr when comarison_expr1 then return_expr1
                [when comarison_expr2 then return_expr2
                when comarison_expr3 then return_expr3
                when comarison_exprN then return_exprN
                else else_expr]

end

Example:
select ename,job,sal,
case job when 'ANALYST' then 1.10*sal
         when 'CLERK' then 1.05*sal
         when 'SALESMAN' then 1.50*sal
         else sal*1.00
           end REVISED_SAL
from emp;

ENAME      JOB              SAL REVISED_SAL
---------- --------- ---------- -----------
SMITH      CLERK            800         840
ALLEN      SALESMAN        1600        2400
WARD       SALESMAN        1250        1875
JONES      MANAGER         2975        2975
MARTIN     SALESMAN        1250        1875
BLAKE      MANAGER         2850        2850
CLARK      MANAGER         2450        2450
SCOTT      ANALYST         3000        3300             
KING       PRESIDENT       5000        5000
TURNER     SALESMAN        1500        2250
ADAMS      CLERK           1100        1155

ENAME      JOB              SAL REVISED_SAL
---------- --------- ---------- -----------
JAMES      CLERK            950       997.5
FORD       ANALYST         3000        3300
MILLER     CLERK           1300        1365
14 rows selected.

1 comment:

  1. I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in IBM Cognos Transformer Design OLAP Models (v10.2.2) - SPVC (J2A82G-SPVC)
    , kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor led training on in IBM Cognos Transformer Design OLAP Models (v10.2.2) - SPVC (J2A82G-SPVC). We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
    For Demo Contact us:
    Name : Arunkumar U
    Email : arun@maxmunus.com
    Skype id: training_maxmunus
    Contact No.-+91-9738507310
    Company Website –http://www.maxmunus.com


    ReplyDelete

Related Posts Plugin for WordPress, Blogger...

ShareThis