Help With A Case Statement With Multiple Variables

I apologize if this is the incorrect Forum for this type of question, but it was the closest one that I could find. I'm pretty new with SQL and am stuck on this issue. I have roughly 26 dates that I need to compare to one another. Each date is tied to a step code. I also have a Stop value that is tied directly to the "max date" of the step codes. So, I need to compare 30 dates against one another to 1st - ID the max date; 2nd - ID if the Stop value is correct; 3rd - if the stop value is incorrect, identify what the correct value would be.
At first, this seemed like it wouldn't be that hard. I wrote a query that found the max date for each step code. Then I realized that multiple step codes could have the same date. So, I tried using this case statement, but I did not get the expected results. Is there a more efficient way of getting what I need? This code seems like it's not necessary and probably the source of my issue.
CASE
WHEN FS25.ACTUAL_COMPLETION_DATE > FS.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS1.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS2.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS3.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS4.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS5.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS6.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS7.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS8.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS9.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS10.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS11.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS12.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS13.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS14.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS15.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS16.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS17.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS18.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS19.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS20.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS21.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS22.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS23.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS24.ACTUAL_COMPLETION_DATE AND L.FORECLOSURE_STOP_CODE <= '8' THEN '9'
ELSE 'UH OH'
END AS "CHANGE FC STOP TO"
Any assistance is appreciated!

I think Igor pointed out a working solution before.
Applying it at your examples (you missed the operator after STOP_CODE, I assume it =):
CASE
WHEN FS25 = GREATEST(FS25, FS24, FS23) AND STOP_CODE = '9' THEN '9'
ELSE 'UH OH'
END AS 'CHANGE STOP CODE TO'
{code}
Be careful at the second example. You are checking:
{code:sql}
FS25 > FS24 OR FS25 IS NOT NULL AND FS24 IS NULL AND FS25 > FS23
OR
FS25 IS NOT NULL AND FS23 IS NULL AND STOP_CODE = '9'
{code}
Remember that AND has higher priority among operators than OR so if FS25 is greater than FS24 and FS23 the condition will be true even if STOP_CODE is not equal 9.
Regards.
Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Help with a CASE statement

    Please help me with a CASE Statement:
    - When ID = 15, 16, 17, 18 then "Bad"
    - when ID = 19, then "Average"
    - when ID = 21, then "Good"
    - else "Null"
    Thank you!!

    Well the 1st thing to do would be to correct my poor spelling... change    Delault : to Default :
    Don't know why you would get an error stating "The result of selection formula must be a boolean". It's working fine on my machine.
    If your ID field is numbers stored text you have a couple different options...
    1) Convert the ID to a number...
    Select  ToNumber({home.noone_ID})
    2) Wrap the ID values in double quotes...
       Case "15", "16", "17", "18" :
          "BAD"
    Even if this were your problem... the error should be something other than the boolean thing...
    Jason

  • Case statement with Subquery

    Case statement with Subquery
    select case when condition then
    i want to execute qr1
    else qr2
    How to implement this ?

    Hi,
    Welcoem to the forum!
    972471 wrote:
    Case statement with SubqueryHow does a sub-query, or a query, figure in this question?
    Be more specific. Post a complete script that you tried, and what output you expected from it. If you got an error, post the complete error message, including line numbers.
    See the forum FAQ {message:id=9360002}
    select case when condition then
    i want to execute qr1
    else qr2
    How to implement this ?Here's one way:
    BEGIN
        CASE
            WHEN  1 = 1
            THEN
                dbms_output.put_line ('Condition was TRUE');
            ELSE
                dbms_output.put_line ('Condition was FALSE or UNKNOWN');
        END CASE;
    END;
    /If the condition involves a query, then you may have to select the results into a variable first, and then use the variable in the CASE statement.

  • Case statement with having null gives default result

    Hello,
    When we write a case statement with a not equal condition <> on a column and if that columns has null value the it gives the else value.
    eg
    Select Column_Name, Case when Column_Name <>Condition then 0 else 1 end as case_test from Table_Name.
    Ideally null is not equal to the condition so the case should return 0 but it returns 1. Can anyone tell me why?

    In addition to the other posts:
    NULL is an unknown value, when you say
      col <> 1
    and col is NULL, we don't know whether col is 1 or something else. Thus the condition evaluates to UNKNOWN. How UNKNOWN is handled depends on the context. In WHEN clauses as well as the IF statments, the effect that the code bracketed by IF/WHEN is not
    entered. That is, UNKNOWN and FALSE yields the same result. In CHECK constraints, it's the other way round. If you have
     CHECK (WHEN col <> 0)
    rows where col is NULL are accepted.
    When you work with SQL, no matter the database product, it's imperative to master three-valued logic, because it comes up all the time.
    As I said, NULL is the unknown value. In practice, NULL has a distinct interpreation depending on the database column. For instance, NULL in a column called EndDate, usually means that the period (or whatever it is) is still open. So often when you work
    with NULL values you use isnull to replace it with some value that fits the context, and finding that value takes some consideration. Blindly doing isnull(col, '') can lead to serious bugs, particularly if col is not a string column.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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.

  • Help with Switch-Case Statement

    How do you get this in a switch-case statement or work with it?
              if (age < 70) {
                        JOptionPane.showMessageDialog(null, "People that are below the 70s are nothing special.");
              else if (age > 69 && age < 80) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 70s are called septuagenarian.");
              else if (age > 79 && age < 90) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 80s are called octogenarian.");
              else if (age > 89 && age < 100) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 90s are called nonagenarian.");
              else (age > 99 && age < 110) {
                        JOptionPane.showMessageDialog(null,  "People that are in their 100s are called centenarian.");
                   }Thanks~

    As per Java Specification, swtich case expects an integer and boolean cannot be used as param for switch.
    In your case switch can be used like this.
    int index = age /10;
    switch(index) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    Your First case
    break;
    case 7:
    your second case
    break;
    case 8:
    third case
    break;
    case 9:
    fourth case
    break;
    default:
    fifth case
    break;
    Take note of the break statements. Its very important. But I wont prefer in this case. Code looks awkward and is not so meaningful.....

  • Case Statement with Group By

    Hello,
    I am trying to build a query that returns the 3 months of a quarter. Below are the two case statements that I am trying to use. I am getting a "Not a group by expression" in the first case statement, and a "nota a single-group group function in the second. Any help with this would be appreciated.
    Thanks, sck10
    SELECT Trev.Revenue_Year,
    CASE
    WHEN Trev.Revenue_Name = 'Jan' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Apr' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Jul' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Oct' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    ELSE SUM(0)
    END AS Month_01,
    CASE
    WHEN Trev.Revenue_Name = 'Feb' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'May' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Aug' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Nov' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    ELSE SUM(0)
    END AS Month_02,
    CASE
    WHEN Trev.Revenue_Name = 'Mar' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Jun' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Sep' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    WHEN Trev.Revenue_Name = 'Dec' THEN Round(SUM(COALESCE(Trev.Revenue, 0)), 1)
    ELSE SUM(0)
    END AS Month_03
    FROM Stage_Report_Revenue Trev
    GROUP BY Trev.Revenue_Year;
    SELECT Trev.Revenue_Year,
    SUM(CASE
    WHEN Trev.Revenue_Name = 'Jan' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Apr' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Jul' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Oct' THEN COALESCE(Trev.Revenue, 0)
    ELSE 0
    END) AS Month_01,
    SUM(CASE
    WHEN Trev.Revenue_Name = 'Feb' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'May' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Aug' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Nov' THEN COALESCE(Trev.Revenue, 0)
    ELSE 0
    END) AS Month_02,
    SUM(CASE
    WHEN Trev.Revenue_Name = 'Mar' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Jun' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Sep' THEN COALESCE(Trev.Revenue, 0)
    WHEN Trev.Revenue_Name = 'Dec' THEN COALESCE(Trev.Revenue, 0)
    ELSE SUM(0)
    END) AS Month_03
    FROM Stage_Report_Revenue Trev
    GROUP BY Trev.Revenue_Year;

    You are getting the "Not a group by expression" error because you are not using in aggregate functions in your select statement. (You are using the aggregate function SUM in the second query)
    The "not a a single-group group function" means you are returning multiple rows of a data when it only expects one.
    HTH

  • Having Trouble with nested Case Statements

    Hi Folks,
    I'm having trouble getting my head round nested case statements. For the life of me I cannot see what I'm missing here (unless my approach is all wrong).
    Any help much appreciated.
    Script:
    set serveroutput on format wrapped
    set feedback off
    set linesize 150
    DECLARE
    /* Set supported version here */
    ora_version VARCHAR2(4);
    unsupp_version EXCEPTION;
    /* Archive Log Info */
    db_log_mode VARCHAR2(12);
    BEGIN
    SELECT SUBSTR(VERSION, 1, 4)
    INTO ora_version
    FROM v$instance;
    SELECT log_mode
    INTO db_log_mode
    FROM v$database;
    CASE
    WHEN ora_version = '10.2' THEN
    DECLARE
    TYPE t_db IS RECORD(
    dflsh VARCHAR2(3),
    dcscn NUMBER);
    v_db t_db;
    BEGIN
    CASE
    WHEN db_log_mode = 'ARCHIVELOG' THEN
    EXECUTE IMMEDIATE 'SELECT INITCAP(flashback_on), current_scn FROM v$database'
    INTO v_db;
    DBMS_OUTPUT.PUT_LINE(' Flashback On : ' || v_db.dflsh);
    DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
    DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
    DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
    END;
    ELSE
    DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
    DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
    END CASE;
    END;
    WHEN ora_version = '9.2' THEN
    DECLARE
    TYPE t_db IS RECORD(
    dcscn NUMBER);
    v_db t_db;
    BEGIN
    CASE
    WHEN db_log_mode = 'ARCHIVELOG' THEN
    EXECUTE IMMEDIATE 'SELECT current_scn FROM v$database'
    INTO v_db;
    DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
    DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
    DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
    END;
    ELSE
    DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
    DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
    END CASE;
    END;
    ELSE
    RAISE unsupp_version;
    END CASE;
    EXCEPTION
    WHEN unsupp_version THEN
    DBMS_OUTPUT.PUT_LINE('');
    DBMS_OUTPUT.PUT_LINE(' Unsupported Version '||ora_version||' !');
    DBMS_OUTPUT.PUT_LINE('');
    END;
    set linesize 80
    set feedback on
    set serveroutput off
    Gives errors:
    END;
    ERROR at line 31:
    ORA-06550: line 31, column 7:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    case
    ORA-06550: line 37, column 1:
    PLS-00103: Encountered the symbol "WHEN"
    ORA-06550: line 50, column 28:
    PLS-00103: Encountered the symbol ";" when expecting one of the following:
    case
    Edited by: milkyjoe on 28-Apr-2010 05:38

    Hi,
    Never write, much less post, unformatted code.
    Indent the code to show the extent of multi-line structures like BEGIN and CASE.
    For example:
    DECLARE
         /* Set supported version here */
         ora_version       VARCHAR2 (4);
         unsupp_version       EXCEPTION;
         /* Archive Log Info */
         db_log_mode      VARCHAR2 (12);
    BEGIN
         SELECT     SUBSTR(VERSION, 1, 4)
         INTO     ora_version
         FROM     v$instance;
         SELECT     log_mode
         INTO     db_log_mode
         FROM     v$database;
         CASE
             WHEN  ora_version = '10.2' THEN
              DECLARE
                  TYPE t_db IS RECORD(
                             dflsh     VARCHAR2(3),
                             dcscn      NUMBER);
                  v_db t_db;
              BEGIN
                  CASE
                      WHEN db_log_mode = 'ARCHIVELOG' THEN
                       EXECUTE IMMEDIATE 'SELECT INITCAP(flashback_on), current_scn FROM v$database'
                                           INTO v_db;
                       DBMS_OUTPUT.PUT_LINE(' Flashback On : ' || v_db.dflsh);
                       DBMS_OUTPUT.PUT_LINE(' Current SCN : ' || v_db.dcscn);
                       DBMS_OUTPUT.PUT_LINE(' Log Mode : ' || db_log_mode);
                       DBMS_OUTPUT.PUT_LINE(' Version : ' || ora_version);
                  END;
    ...The code above is what you posted, with some whitespace added.
    The error is much clearer; the last CASE statement concludes with END, but CASE blocks always have to conclude with END CASE .
    Why are you using a nested BEGIN block in the code above? Are you plannning to add an EXCEPTION handler later?
    When posting formatted text on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • CASE statement with MIN?

    I am trying to write a case statement which says when STAT is E select the MIN(TERM)
    If there is multiple TERM which are both low just pick any. Want one per row per ID.
    Is that possible by using case?
    Thanks.
    CREATE TABLE DAN_GR2
    (ID    VARCHAR2(12),
    TERM    VARCHAR2(12),
    STAT VARCHAR2(12))
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('1','5','E')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('1','2','D')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('1','9','E')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('1','5','E')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('2','1','E')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('2','10','E')
    INSERT INTO DAN_GR2 (ID, TERM,STAT) VALUES ('3,'10','D')
    ID      TERM     STAT
    1     5     E
    1     2     D
    1     9     E
    1     5     E
    2     1     E
    2     10     E
    3       10      DWant
    ID   MIN_TERM  
    1     5     
    2     1
    3     NULLUsing:Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    Edited by: Chloe_19 on 12/09/2012 18:07

    Hi,
    So, you don't want to ignore the whole row when stat != 'E' (that would ignore the only row with id='3'). Putting the condition 'stat = 'E' in the WHERE clause sill ignore the row, so that's not what you want.
    You just want to ignore the term column. Put the same condition in a CASE expression that only contols that column.
    Here's one way:
    SELECT       id
    ,       MIN ( CASE
                     WHEN  stat = 'E'
                  THEN     term
                 END
               )          AS min_e_term
    FROM      dan_gr2
    GROUP BY  id
    ORDER BY  id
    ;

  • 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

  • Case Statement with excel data source

    When trying to create a case statement in the RPD I get the following error in answers when selecting from the column.
    Listed is the RPD column select statement CASE EMPHOURS.EMPHOURS_DIM.PAYCODE WHEN 'OT' THEN 'Overtime' END
    Listed is the error I receive in answers:
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 16001] ODBC error state: 37000 code: -3100 message: [Microsoft][ODBC Excel Driver] Syntax error (missing operator) in query expression 'case T24.[PAYCODE] when 'OT' then 'Overtime' end'.. [nQSError: 16014] SQL statement preparation failed. (HY000)
    The statement works fine when I use oracle RDBMS as the data source and not excel.
    Regards

    Hi Sophia,
    Could you please edit Database>Features in this there will be a feature "CASE_IF_SUPPORTED" and another CASE related feature which you need to change and check in this features.
    Regards,
    Som

  • Case statement with group by clause

    SELECT STP, CASE WHEN Alternate IS NULL THEN 3 ELSE 4 END as Ind,
    CASE WHEN Alternate IS NULL THEN 'New Address' ELSE 'New Location' END as Description , Count(*) Rec_Cnt
    FROM t_Ids
    group by STP, CASE WHEN Alternate IS NULL THEN 3 ELSE 4 END, CASE WHEN Alternate IS NULL THEN 'New Address' ELSE 'New Location'
    ORDER BY 1,2,3
    I need a query something like this. Does anyone has any idea on this???

    You're missing the END on the GROUP BY Case statement, but otherwise this looks fine.
    What problem are you having?
    Also, please post DDL
    Thanks
    Carl

  • CASE Statement for Multiple Criteria

    Hello,
    I need to write a query that will give me a count of customers that fall in three different categories:
    < 1 year
    1 to 3 years
    3 yearsI have written the code to bring me back the 1st set of criteria (< 1 yr). I am using the date connected to a customer's account(s) to return the oldest date attached to an account to put that customer in the appropriate bucket. Below is the code I have for the first piece:
    SELECT COUNT(*) AS One_Year_Or_Less
    FROM
    (SELECT c.lname||', '||c.fname AS Name, MIN(a.contractdate) AS ContractDate
    FROM account a, customer c
    WHERE a.custnbr = c.custnbr
    GROUP BY c.lname, c.fname) yr
    WHERE yr.contractdate BETWEEN TO_DATE('03/02/2005', 'MM/DD/YYYY')
    AND SYSDATE
    The above query runs and returns what I beleive to be an accurate count of customers who fall in the 1 year or less range. My question is; how can I add the criteria of 1 to 3 years and > 3 years to this query. I need to have 3 seperate columns (or 3 seperate rows) that contain the heading of the specific criteria and then the count for that criteria. I was thinking of trying to use a CASE statement but I am unsure of exactly how to do that. Perhaps I could somehow create 3 seperate sub-queries to acheive my goal. Any help with this issue will be greatly appreciated. Thank you.
    Dave Y

    Here's another way. It will only count those that meet the criteria, otherwise it will sum a 0. If you just want 1 row returned with the counts, there's no need for a GROUP BY
    SELECT SUM(CASE
                   WHEN contractdate >  add_months(sysdate,-12) THEN 1
                   ELSE 0
               END) less_than_1_year
          ,SUM(CASE
                   WHEN contractdate >= add_months(sysdate,-36)
                   AND  contractdate <= add_months(sysdate,-12) THEN 1
                   ELSE 0
               END) from_1_to_3_years
          ,SUM(CASE
                   WHEN contractdate <  add_months(sysdate,-36) THEN 1
                   ELSE 0
               END) over_3_years
    FROM ...

  • Need help to write case statement

    Hi Guys,
    I have dashboard in which its has pprompt called PROPMT1 in that prompt it has three values A,B,C
    but iwant the full abbreviation of those values like A=APPLE B=BOY and C=Cindy
    and also in the report i have the coloumn is prompted by PROMPT1 which has again A,B,C values that need to be modified as A=APPLE B=BOY and C=Cindy
    how can i do it with case statement.

    For the prompt, write this in the Show window>SQL Results:
    1) CASE WHEN 1=0 THEN char_columnname ELSE 'A = APPLE' END FROM "your subject area" UNION ALL CASE WHEN 1=0 THEN char_columnname ELSE 'B = BOY' END FROM "your subject area" UNION ALL CASE WHEN 1=0 THEN char_columnname ELSE 'C = Cindy' END FROM "your subject area"
    2) Save the prompt to a presentation variable, pv_choice
    This will give you your three values. Make sure you use a CHAR column, doesnt matter what column, though.
    For the report,
    1) Create a BINS column on the column that contains the A, B, C values and make the BINS A = APPLE, B = BOY, C = Cindy just like the prompt values.
    2) Now put a filter on this BINS column and set it equal to your pv_choice presentation variable.
    That's it.
    NOTE: Obviously, if you want the prompt values to just say "APPLE," "BOY," and "Cindy," then take off the 'A = ', 'B = ' and 'C = ' appropriately. Same for the BINS in your report.
    Edited by: David_T on Jun 8, 2011 10:57 AM

  • Please Help: Trouble with nested CASE statement and comparing dates

    Please tell me why the query below is always returning the bold null even when the start_date of OLD is greater than or equal to the start_date of NEW.
    What I want to do is get the difference of the start_dates of two statuses ( Start_date of OLD - Start_date of NEW) if
    1. end_date of NEW is not null
    2. start_date of OLD is greater than start_date of NEW
    else return null.
    select id,
    case when max(end_date) keep (dense_rank last order by decode(request_wflow_status,'New',1,0),start_date) is null then
    null
    else
              case when max(decode(status,'OLD',start_date,null)) > max(decode(status,'NEW',start_date,null))
              then max(decode(status,'OLD',start_date,null)) - max(decode(status,'NEW',start_date,null))
    else
    null
    end
    end result
    from cc_request_status where id =1
    group by id;

    Avinash,
    Thank you for your help.. Here is a more description of my problem..
    Here is a sample of data I have for a table with four columns (id,status,start_date,end_date)
    What I need to do is to get difference of the start dates of the maximum available dates, if data is valid. The pseducode is as follows:
    IF end_date of New status is null
    THEN return null
    ELSE
    IF start_date of old >= start_date of new
    THEN return (start_date of old - start_date of new)
    ELSE return null
    I used the following query but always return the bold null
    select id,
    (case when max(end_date) keep (dense_rank last order by decode(status,'new',1,0),start_date) is null then
    null
    else
              (case when max(decode(status,'old',start_date,null)) >=
              max(decode(status,'new',start_date,null))
              then max(decode(status,'old',start_date,null)) - max(decode(status,'new',start_date,null))
    else
    null
    end)
    end) result
    from tbl where id =1
    Based on the below sample, I expected to get the following result; 14-Mar-07 - 16-Feb-07 which is the difference of the maximum start_dates of the two statuses. However the query is not working.. Please help me.. Thank you..
    Id    Status    start_date      end_date
    1     new      03-Feb-07      07-Feb-07
    1     new      16-Feb-07      21-Feb-07
    1     old      '10-Mar-07      12-Mar-07
    1     old      '14-Mar-07      16-Mar-07

Maybe you are looking for

  • How do I restore a failed external hard drive using Time Machine?

    I have an external hard drive connected to my iMac that is being backed up with Time Machine.  I just realized that should it one day fail and no longer appear as a connected device, I'm not sure how to restore its data to another external drive.  Wh

  • To remove the cancelled Billin doc from VFX3

    Hi all, We have a cancelled billing doc in VFX3. This is because the accounting document is not generated for the same due to some foreign exchange value mismatch as the biiling doc was created in one month and cancelled in another month. So credit m

  • Package question

    say i have two java programs. program a, program b. also a contains an instance of b. now, both compile fine when i have them in my "java" directory. when i put the line package com.bean in both, b compiles but a will not. the error for a is cannot r

  • How to Genarates Keys in MDM

    Hi Frnds, I want to know some more information about MDM Keys, Suppose i am having one Data Base Record its having 1000 employees information , I'm storing this document in MDM,But in Dta Base its already having Employee number for unique identificat

  • Renew-subscription doesnt work

    Hi, I have a lapsed subscription to AE that I needed to renew. I went online paid for my renewal I open my software but it keeps saying i need to renew my subscription! I have logged out , restarted my computer, I have waited hrs before opening the s