If then else in SQL

I've the following query :
SELECT
      cdv.location_id,
       cdv.address1,
       cdv.address2,
       SUM(aps.amount_due_remaining) TOTAL_BALANCE,
       SUM(DECODE(SIGN(TO_DATE(due_date,'DD-MON-RRRR')-TO_DATE(SYSDATE,'DD-MON-RRRR')),1,aps.amount_due_remaining,0)) NOT_YET_DUE_BAL
FROM       Table1 cdv,
          Table2 al,
          table3 rctt,
          Table4  aps,
          table5 rct,
          table6 sot
WHERE    rct.column1 = aps.column1
AND    aps.column1 = rctt.column2
AND    aps.column2 = cdv.column3
AND    rctt.name = al.description(+)
and    rct.sot_id = sot.sot_id
GROUP BY
       cdv.cdv.location_id,
       cdv.address1,
       cdv.address2
HAVING SUM(aps.amount_due_remaining) > 0
In the above query if
aps.currency <> sot.currency then I want to display
SUM(aps.amount_due_remaining*aps.exchange_rate) TOTAL_BALANCE,
       SUM(DECODE(SIGN(TO_DATE(due_date,'DD-MON-RRRR')-TO_DATE(SYSDATE,'DD-MON-RRRR')),1,aps.amount_due_remaining*aps.exchange_rate,0)) NOT_YET_DUE_BAL
ELSE
  SUM(aps.amount_due_remaining) TOTAL_BALANCE,
       SUM(DECODE(SIGN(TO_DATE(due_date,'DD-MON-RRRR')-TO_DATE(SYSDATE,'DD-MON-RRRR')),1,aps.amount_due_remaining,0)) NOT_YET_DUE_BAL
IF I use CASE for this, I'm getting ORA-00979 Not a grop by expression error
Thanks,
Kiran

user518071 wrote:
In the above query if
aps.currency <> sot.currency then I want to display
SUM(aps.amount_due_remaining*aps.exchange_rate) TOTAL_BALANCE,
       SUM(DECODE(SIGN(TO_DATE(due_date,'DD-MON-RRRR')-TO_DATE(SYSDATE,'DD-MON-RRRR')),1,aps.amount_due_remaining*aps.exchange_rate,0)) NOT_YET_DUE_BAL
ELSE
  SUM(aps.amount_due_remaining) TOTAL_BALANCE,
       SUM(DECODE(SIGN(TO_DATE(due_date,'DD-MON-RRRR')-TO_DATE(SYSDATE,'DD-MON-RRRR')),1,aps.amount_due_remaining,0)) NOT_YET_DUE_BAL
Your query groups by:
GROUP BY
       cdv.cdv.location_id,
       cdv.address1,
       cdv.address2
Each group can have multiple rows. So what if some rows in one (or more) of the groups have aps.currency <> sot.currency and some rows in same group have aps.currency = sot.currency. As you can see, issue is not with CASE, but with your logic. Unless you want to see both totals per group: one for rows where aps.currency <> sot.currency and other for the rest of the rows. Then you coul use something like:
       SUM(CASE WHEN aps.currency <> sot.currency THEN aps.amount_due_remaining END) TOTAL_BALANCE1,
       SUM(CASE WHEN aps.currency <> sot.currency THEN NULL ELSE aps.amount_due_remaining END) TOTAL_BALANCE1
Also, due_date is DATE, right? Converting DATE to DATE causes implicit conversion and might return unexpected results. Use
SUM(DECODE(SIGN(TRUNC(due_date)-TRUNC(SYSDATE)),1,aps.amount_due_remaining*aps.exchange_rate,0)) NOT_YET_DUE_BAL
Or better:
SUM(CASE WHEN TRUNC(due_date) > TRUNC(SYSDATE) THEN aps.amount_due_remaining * aps.exchange_rate ELSE 0 END) NOT_YET_DUE_BAL
SY.

Similar Messages

  • Select in CASE statement or in IF-THEN-ELSE

    I have been struggling for a week with a problem and still can't solve the way I want.
    Given four text fields in page : p1_name, p1_place_name, p1_place_number and p1_place_init_letter - where user types text and press 'Search' button to see the results.
    p1_name finds results in table EMPLOYEES
    p1_place_name, p1_place_number and p1_place_init_letter find results in table PLACES
    the two tables are linked by id_place field
    I would like reports to be shown depending on search results:
    - if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place = PLACES.id_place then a single report shows only employee row
    - if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place # PLACES.id_place then two reports showing 1) employees with name = :p1_name and 2) places with name, number and init_letter = :p1_.....
    - if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist then a message with 'NO EMPLOYEE' and report shows only places where name, number and init_letter = :p1_.....
    - if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then report shows only employee row where name = :p1_name and message with 'NO PLACE'
    - if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then messages 'NO EMPLOYEE' and 'NO PLACE'
    I do NOT know if it is possible, and if it is, then what do I have to use : IF - THEN - ELSE or CASE ?
    I tried to build HTML report region conditionally shown for each situation, but they do not work the way I want.
    Could you please help me ?
    Thank you in advance !

    Agree with Dan. Use a dedicated report region for a unique query. Use a rendering condition to determine if that reporting region must be rendered (i.e. whether or not that reporting query must be executed ).
    The alternative is creating a function that constructs the SQL query dynamically, based on the user supplied values for page items. Use the function as the source for the reporting region, instead of a SQL statement. (this is similar to creating a ref cursor for a client, minus the actual step to create the ref cursor - instead the source SQL for that ref cursor is returned).
    Also consider asking your Apex questions in the dedicated Apex forum on OTN.

  • If then else emulation

    it is not very efficient, but nevertheless works.....
    since xmlp is very limiting on the size of a statement, you need to keep it simple.....
    Its better then using multiple if statements which is what we had to do in the past.
    5.6.3 is supposed to have a if-then-else statement so can't wait to get there.....
    here is the code....
    <?choose:?>
    <?when:sum(LINE_UNIT_SELLING_PRICE)<400?>LOW<?end when?>
    <?when:sum(LINE_UNIT_SELLING_PRICE)>399 and sum(LINE_UNIT_SELLING_PRICE)<4000?>MED<?end when?>
    <?otherwise:?>HIGH<?end otherwise?>
    <?end chose?>

    other helpful syntax
    <? format-date: @orderdate; 'DD-MMM-YYYY' ?>
    <? format-number: ./price; 'L999G999D99' ?>
    TOTAL ITEMS: <? count(items/item) ?> works like sql count
    <? for-each:items/item ?> Item <?position() ?> <? end for-each?> works like sql rownum function
    to set and get variables
    Hope someone finds these useful....

  • How to do IF THEN  ELSE logic in Workflow?

    I need to do "if then else" logic in Workflow. The key part of the probem is that there are several "else" (elsif) possibilities, so I can't use a Boolean or Yes/No as a return result code. When I use a function, I can't see a way to "check" the value before it passes to a next process. HELP!

    Whether you are using a function as your comparator or the Standard WF Compare Operators, this can be done. I will explain two scenarios, one with your own written functions as the comparator and the other using the standard Compare Text function.
    Create a PL/SQL procedure that returns a boolean. In this procedure you would pull two attributes from the workflow, the test case and the value you want to compare to. You would check to see if they are equal and return true, otherwise false. I do not know what you are trying to compare in your if statement, but whatever it is, if its true, return true, otherwise false.
    Now in the workflow, you would put a couple of these in your process diagram representing each if statement. Set the two (or more) attributes in the Node Attributes tab of each function node to the values you want to compare. For the first node, have the <true> transition go to whatever you want done and then to an END node. Have the <default> or <false> transition point to the next function node you have. Do the same for each one except at the last one, its only transition would be <default> and that would go to END. This way if the first function resolves true, it will do whatever should be done and then skip the rest of the conditions. If its false, it will go to the next conditional. The last one will be gotten to only if every other conditional was false that would be your final else statement.
    To do this with the Compare Text option, have the same set up in your workflow diagram exception have the <EQUALS> be your true path and the <DEFAULT> transition go to the next compare text node.
    -->O-{default}->O-{default}->O->default
         |                 |                 |             |
        true           true            true           |
         |                 |                 |             |
      doWork     doWork     doWork      else
         |                 |                 |             |
          ---------------->---------------->------------|
                                                          |
                                                      end

  • IF THEN ELSE in DATA TEMPLATE NOT IN RTF

    Hi,
    Can any one tell me How to Implement IF THEN ELSE or DECODE or CASE Logic in a DATA TEMPLATE not in RTF
    as I saw loads of Post about implementing them in RTF not in the Template itself.
    I have a requirement please click this below for the Detailed Version of this Post, Else Please Just give me a Snippet from which i can Implement the IF THEN ELSE Logic in a DATA TEMPLATE( the .xml file) bu please not via a RTF not using PL/SQL Package
    Logic to select Report name based on User's input.
    Thanks
    vasanthanand

    Hello
    I am looking to do the same type of thing did you ever get an answer without having to use a RTF format perhaps in another forum or through investigation?

  • Can a user input query in WFA have IF THEN ELSE

    Below is my query and when I save it WFA throws the following error.Illegal user input query 'IF '${vfilerName}' != 'vfiler0' THEN
    SELECT
    vol.name,
    array.ip AS 'array.ip'
    FROM
    storage.vfiler AS vfl,
    storage.volume AS vol,
    storage.array AS array
    WHERE
    vol.vfiler_id = vfl.id... HERE is my actual query. IS an  IF THEN ELSE supported or I am doing something wrong.... IF '${vfilerName}' != 'vfiler0' THEN
    SELECT
    vol.name,
    array.ip AS 'array.ip'
    FROM
    storage.vfiler AS vfl,
    storage.volume AS vol,
    storage.array AS array
    WHERE
    vol.vfiler_id = vfl.id
    AND vfl.name = '${vfilerName}'
    AND vol.array_id = array.id
    AND (
    array.ip = '${arrayName}'
    OR array.name = '${arrayName}'
    AND vol.name = '${volName}'
    ORDER BY
    vol.name DESC
    ELSE
    SELECT
    vol.name AS 'name',
    array.ip AS 'array.ip',
    array.name AS 'array.name'
    FROM
    storage.volume AS vol
    JOIN
    storage.array AS array
    ON vol.array_id = array.id
    WHERE
    array.ip = '${arrayName}'
    OR array.name = '${arrayName}'
    END IF

    Yes you can use IF, but you cannot use Select ..... IF.... Select... ELSE.... SELECT... . It's not a valid SQL statement. If you want many SELECT statements you should use UNION but most of the time you won't need it. I've create a query that uses and it may help you. Take a look at the way I use IF. SELECT
        export_policy.name 'Nome das políticas',
        GROUP_CONCAT(if(rw_rule='sys'
        OR rw_rule='any',
        export_rule.clientmatch,
        null)) 'REGRAS RW',
        GROUP_CONCAT(if((ro_rule='sys'
        OR ro_rule='any')
        AND rw_rule='none',
        export_rule.clientmatch,
        null)) 'Regras RO'
    FROM
        cm_storage.export_policy
    INNER JOIN
        cm_storage.export_rule
            ON export_policy.id=export_rule.policy_id
    JOIN
        cm_storage.vserver
            ON export_policy.vserver_id=vserver.id
    WHERE
        vserver.name='${VserverName}'
        AND export_policy.name!='default'
    GROUP BY
        export_policy.name You can have some reference of IF usage here: https://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_if

  • Sum function within if/then/else (xdofx:if)

    I'm attempting to display a total at a particular group within my report. This total is conditional and should choose to display a placeholder value or the sum of another placeholder value (in a child group).
    I have been able to vary my output based on the value I want to check: FIXED_QUOTE_FLAG - I have the if/then/else working in a simplified fashion
    I can display literals and some placeholders correctlly eg. print a literal value of 00110011 or the value of placeholder QUOTED_PRICE
    I can also display a calculated placeholder, using sum within the group I am concerned with: sum (current-group()/ACTIVITY_CHRG)
    But when I try to get everythign working together ...
    I cannot get the sum to work inside the if/then/else condition. The result is NULL (blank in HTML output).
    The following is the snippet which is not working correctly:
    <?xdofx:if FIXED_QUOTE_FLAG = 'Y' then QUOTED_PRICE else sum (current-group()/ACTIVITY_CHRG) end if?>
    Message was edited by:
    gareth_adamson

    To answer you first question, perhaps sum is not a supported function in the xdofx namespace. It's annoying when this problem comes up because xdofx namespace seems to be the only way to do if then else clauses. I'm not entirely certain on the above, but you could resort to using BI Publisher's built-in if statement.
    For your problem, something like this:
    <?if: FIXED_QUOTE_FLAG='Y'?>
    QUOTED_PRICE
    <?end if?>
    <?if: FIXED_QUOTE_FLAG!='Y'?>
    <?sum(current-group()/ACTIVITY_CHRG)?>
    <?end if?>
    EDIT:
    There is a way to do if else without xdofx namespace. It is done with <?choose:?> <?when:?> and <?otherwise:?> tags. Here is example syntax copied from Tim Dexter's blog:
    <?choose:?>
    <?when:count(TRX_NUMBER) > 0?>
    Invoice Table
    <?end when?>
    <?otherwise:?>
    No Data Found
    <?end otherwise?>
    <?end choose?>
    To answer the second question about a running total, you will need to use the <?xdoxslt:set_variable($_XDOCTX,'var_name',var_value)?> and the <?xdoxslt:get_variable($_XDOCTX,'var_name')?>. This method of working with variables is the only method that allows you to update a variable. This makes it good for running totals. Consult the official user guide under "Creating an RTF Template" the section about using variables and calculating running totals.
    So, in your problem, once you get the first part working, you will have to add that value to your running total. It will look something like this:
    <?xdoxslt:set_variable($_XDOCTX,'running_total',xdoxslt:get_variable($_XDOCTX,'running_total') + conditional_value)?>
    Remember to initialize the running total to zero! Hope this helps.
    Thanks,
    Matt Soukup
    Message was edited by:
    Matt Soukup

  • Problem with IF THEN ELSE in RTF template

    HI ALL,
    I have two layouts in the RTF template. Based on the parameter value it has to show the value.
    For example if P_State='United States' then first layout should come. else second one should come.
    I tried to use the IF Then else logic through the form field but i am getting error.
    Please help on this to get it.
    Regards
    Boopathi

    You can do that.
    i guess, the syntax you are using is wrong.
    please refer documentation or this forum for choose:
    Use choose statement. it s better.
    Or send me the template to my id in my profile. or upload it here http://apps2fusion.com/forums/viewforum.php?f=60

  • If Then Else Statement in SAP R/3 BW

    Hi,
    Does anyone know how to create an If Then Else statement in BEX?
    Thanks,
    Mounika.

    Hi mounika,
    do this way
    If 'material number' > 0.
    rslt = 'enter into table'.
    else.
    rslt = 15.
    endif.
    A True condition always evaluates to 1, a False condition evaluates to 0.
    for more quieries in bw ..pls go through  the link
    http://sap.ittoolbox.com/groups/technical-functional/sap-bw
    pls reward if helps,
    regards.

  • If-then-else in a select statement

    hi, is it possible to make a if-then-else in a select query, something like:
    select name, age, if(sex=f,1,2) as my_columnn from table1;
    thx.

    Hallo,
    yes it is possible:
    1. with decode
    select name, decode(sex, 'f',1,2) as your_column from table1;
    2. with case
    select name, case when sex='f' THEN 1 ELSE 2 END) as your_column from table1;
    Regards
    Dmytro

  • Problem in If-Then-Else formula in report

    Hello guys!
    I use an If-Then-Else statement in a Calculated Key Figure (Cf. <a href="http://help.sap.com/saphelp_nw04s/helpdata/en/23/17f13a2f160f28e10000000a114084/content.htm">Conditional Calculations</a> ) and it works great with basic calculations.
    I have a query (done in BI 7.0) where I display, for each calendar months (via 0CALMONTH), the usage (stored in a normal key figure in hours) of several products.
    I need to take into account only the products that have been used for at least 60% of the time of the highest product for each month. I a single product, for a month, has been used less than 60% of the highest one, it should be considered as not being used at all (so the calculated usage would be = 0), otherwise, its usage is counted as normal.
    In order to achieve this, I thought I would display the normal usage (the regular key figure) in column A, a calculated key figure that determines the MAXimum usage for each month in column B (which should be the same for all products) and another calculated key figure that displays the result of the If-Then-Else statement in column C.
    In rows, I have 0CALMONTH and the products.
    HOWEVER, when I do this, the result is incorrect. This is probably because to determine the MAX usage, I use a local calculation option, which displays the correct maximum usage on each row but it's not correct when used somewhere else.
    <b>MY QUESTION IS: HOW can I display the maximum usage for a month on all rows without using the calculation option (and therefore would be correctly used by the If-Then-Else statement. I tried an aggregation exception but it doesn't really work (it works only on the total, but I need to do the calculation on each individual row).</b>
    <u><b>Any useful comment will be greatly appreciated </b></u>
    Thanks in advance!

    Hi Francal ,
    Have you tried it . The constant selection will work if you have defined the calculated key figure correctly i.e. Aggreagtiomn "Max" with "product" as ref characteristic. Then you have to use this calculated key figure in your query , restrict it by "product" and make it a constant selection.
    The calculated key figure it self  will bring the highest usage for Month + product + ( any other characteristic you have in query ) but this will only apply to result . If you use constant seelction on top of it it will make sure that you see same value for all product for a particular month( and other characteristic combinations if you have ).
    I have built similar queries and it works . By the way which versions of backend and frontend you have ??
    Regards
    Sanjay

  • Problem with if-then-else using BI Answers dataset

    Hi, I'm having issues using the if-then-else logic with a BI Answers dataset. I'm running two versions of a report - one that access the SH schema tables directly, and one that uses a BI Answers dataset based on the SH schema.
    My problem is with the if-then-else operator. It works fine against the relational tables when I use the following syntax:
    <?xdofx:if CUST_GENDER = 'M' then 'Mr.' else 'Ms.' end if?>
    However, when I go against a BI Answers report, the name of the field changes from CUST_GENDER to Customers._Cust_Gender_. If I make an exact find and replace on the if-then-else code, it doesn't work (nothing at all displays)
    <?xdofx:if Customers._Cust_Gender_ = 'M' then 'Mr.' else 'Ms.' end if?>
    Can anyone help?
    Thanks,
    Scott

    Is it possible that any of the fields have null values?  If so, see my blog post about null handling in Crystal for more information:  What is Null and Why is it Important for Crystal Reports | SAP BI BLOG
    -Dell

  • Query if-then-else logic with calculation

    Hello,
    I want to calculate within a BEX-formula.
    I have two key-figures:
    - Quantity
    - Value
    The logic should be like this:
    IF Value > 0 THEN Value / Quantity ELSE 0
    ( / means: divided)
    How can I reach this?
    The URL
    http://help.sap.com/saphelp_nw70ehp1/helpdata/de/e3/e60138fede083de10000009b38f8cf/frameset.htm
    does not help me.
    Thanks for your help,
    Thomas

    That is the way to perform if then else...
    As long as boolean operations returns 0 or 1 you must play with that in order to get the desired result.
    In case you have DIV problems you can use this operator:
    NDIV0 (x): Is equal to 0 with division by 0, otherwise x.
       NDIV(<Expression>)
    Delivers 0 if the expression named in <Expression> gives a division by 0 in
    the calculation. Otherwise, the result is the value of the expression.
    Is used to
      - Avoid the output of an error message
      - Continue calculating with a defined result
    Please give an example if I am missing something.
    Regards,
    Sebastian,.

  • Java If/Then/Else Statement

    Hello,
    Just wondering if it is possible to call one java file from within another.
    I'm thining wiht an if.then/else statement similar to
    If x==true
    then run file1.java
    else run file2.java
    any examples of this, or if it is even possible would be appreciated.

    This is something like what I would do.
    public class FileRunner {
        public static void main(String [] args) {
            if ( args[0].equals("file1") {
                File1 file1 = new File1();
                file1.init() //method you define in File1 that runs everything that would've been in the File1's main method
            } else if (args[0].equals("file2") {
                File2 file2 = new File2();
                file2.init() //method you define in file2 that runs everything that would've been in the File2's main method
            } else {
                System.err.println("Invalid argument");
                System.exit(1);
    java.exe FileRunner.class file1
    java.exe FileRunner.class file2The other method is to start a new jvm from within java, but that gives you less control than this imo.

  • Nested if-then-else with double condition

    Hi everybody, I tried to see on the forum how to build a complex if-then-else statement....but I didn't still find an answer
    So, I'll explain my situation:
    First I have to check if the field PROJ_DT_TO is null or not and then the language parameter:
    1. if the field PROJ_DT_TO IS NULL then I have to check the language parameter:
    a) if this last one is equal to 'English' I want to write inside my template 'Today',
    b) if instead is equal to 'Greek' I want to write 'Σήμερα'
    2. else if the field PROJ_DT_TO IS NOT NULL, again, I have to check the language parameter:
    a) if this last one is equal to 'English' I have to write <?format-date:PROJ_DT_TO;'MMMM yyyy'?>
    b) if instead is equal to 'Greek' I have to write <?format-date-and-calendar:PROJ_DT_FR;‘MMMM yyyy’;'GREGORIAN';'Europe/Athens'?>
    I used the following syntax...but it didn't work...
    <?choose@inlines:?>
    <?when@inlines:PROJ_DT_TO=''?>
    <?xdofx:if $p_language = 'Ελληνικά' then 'Σήμερα' else if $p_language = 'Αγγλικά' then 'Today' end if?><?end when?>
    <?otherwise@inlines:?>
    <?xdofx:if $p_language = 'Ελληνικά' then <?format-date-and-calendar:PROJ_DT_FR;‘MMMM yyyy’;'GREGORIAN';'Europe/Athens'?> else if $p_language = 'Αγγλικά' then <?format-date:PROJ_DT_TO;'MMMM yyyy'?> end if?>
    <?end otherwise?>
    <?end choose?>
    The first piece, until the first <?end when?> instruction works....it's the <?otherwise@inlines:?> and the rest which doesn't work.....
    If, instead, I use (without reaching my goal):
    <?choose@inlines:?>
    <?when@inlines:PROJ_DT_TO=''?><?xdofx:if $p_language = 'Ελληνικά' then 'Σήμερα' else if $p_language = 'Αγγλικά' then 'Today' end if?><?end when?>
    <?otherwise@inlines:?>
    <?format-date:PROJ_DT_TO;'MMMM yyyy'?><?end otherwise?>
    <?end choose?>
    I see the date PROJ_DT_TO even if always in the date format 'MMMM yyyy'
    Anybody knows how can I rewrite my statement in order to reach the if-then-else situation I metioned above ?
    Thanks in advance
    Best Regards
    Alex

    Hi Vetsrini, thaks for your answer and your hint !!
    I tried your code, but without the command 'when@inlines' doesn't work...
    So I tried this :
    <?choose@inlines:?>
    <?when@inlines:PROJ_DT_TO=''?>
    <?xdofx:if $p_language = 'Ελληνικά' then 'Σήμερα' else if $p_language = 'Αγγλικά' then 'Today' end if?>
    <?end when?>
    <?otherwise@inlines:?>
    <?format-date:PROJ_DT_TO;'MMMM yyyy'?>
    <?end otherwise?>
    <?end choose?>
    and It works..
    But, look at this ! I discovered on the manual that inside the Preferences it's possible to set the Report Locale with the language you want.....and if I set my Report Locale in Greek, using the code above I correctly see all dates in Greek....but ALWAYS !!
    I need to see dates in Greek or English dinamically according to the value of the parameter p_language passed inside the template at the beginnig (<?param@begin:p_language?>).
    Even if inside the code there is the double condition ($planguage = 'Ελληνικά' or $p_language = 'Αγγλικά') for the two cases PROJ_DT_TO='' or PROJ_DT_TO !='', I see ALWAYS dates in the language set inside the Locale Report....
    Is there a way to manipulate the Report Locale Setting and make it dinamic ?
    Thanks in advance
    Alex
    So this preference is static, even if inside my report I have the parameter p_language I can see the data and headings with

Maybe you are looking for