Case Statements based on a condition.

Hi All,
I have 2 EXEC statements independent of each other which is in the if loop. But based on a condition which I check in the query starting I need to mention whether to execute only @Statment1 or only @Statement2 or both @Statment1  and @Statment2.
Please let me know if this is not clear.
IF x<y
BEGIN
If SearchCondition = 'Search'
then EXEC(@Statement1)
else  
EXEC (@Statement1)
EXEC (@Statement2)
END
set @x = @x+1 
Can some one please suggest a way.
Thanks,
VSP

First just define the conditional branching, then fill out the dots:
IF x<y BEGIN
IF SearchCondition = 'Search' BEGIN
END
else BEGIN
END
ELSE BEGIN
END
set @x = @x+1
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • Why doesn't this case statement work?

    SELECT
    case when PRODUCTS.PRODUCT_NAME in
    select case when rank() over(order by ( sum(ag.RX_CNT) ) desc) < 6 then ( p.PRODUCT_NAME ) else 'XXXX' END RankedProduct
    FROM
    PAP_MONTHLYTIME_DIM m,
    PAP_PRESCRIPTIONS_DEMOG_AGG ag,
    PRODUCTS p,
    PAP_ENROLLMENT_FLAGS_DIM f
    WHERE
    ( m.MONTHLYTIME_DIM_ID = ag.MONTHLYTIME_DIM_ID )
    AND ( ag.ENROLLMENT_FLAGS_DIM_ID = f.ENROLLMENT_FLAGS_DIM_ID )
    AND ( p.PRODUCT_ID = ag.PRODUCT_DIM_ID )
    AND ( f.ACTIVE_FLAG = 'Y' )
    AND m.CALENDAR_YEAR_MONTH = '2007-04'
    GROUP BY
    m.MONTH_END_DATE,
    p.PRODUCT_NAME
    then
    ( PRODUCTS.PRODUCT_NAME ) else 'All Other' end as ProdNm,
    PRODUCTS.PRODUCT_NAME,
    sum(PAP_PRESCRIPTIONS_DEMOG_AGG.RX_CNT)
    FROM
    PRODUCTS,
    PAP_PRESCRIPTIONS_DEMOG_AGG
    WHERE
    ( PRODUCTS.PRODUCT_ID=PAP_PRESCRIPTIONS_DEMOG_AGG.PRODUCT_DIM_ID )
    GROUP BY
    PRODUCTS.PRODUCT_NAME
    The first case statement is not working properly. First off - I know I can do this without the subquery in the case statement, but it's then tied to the Month and I don't want that.
    The result set of the subquery contains valid product_names that match EXACTLY (I added LTRIM RTRIM just in case), but the ProdNm field still evaluates to "All Other" for them. If I change the subquery to something basic and remove the rank function, it works, but of course I need that function. My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated).
    Any ideas?
    Thanks.

    My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated). It looks like the queries ARE somehow correlated. Consider the two simplified queries:
    michaels>  SELECT   ename, deptno,
             CASE
                WHEN deptno IN (
                       SELECT CASE
                                 WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                    THEN deptno
                                 ELSE 1000
                              END
                         FROM dept)
                   THEN 'Found'
                ELSE 'NOT Found'
             END FOUND
        FROM emp
    ORDER BY deptno
    ENAME          DEPTNO FOUND   
    CLARK              10 NOT Found
    KING               10 NOT Found
    MILLER             10 NOT Found
    JONES              20 NOT Found
    FORD               20 NOT Found
    ADAMS              20 NOT Found
    SMITH              20 NOT Found
    SCOTT              20 NOT Found
    WARD               30 NOT Found
    TURNER             30 NOT Found
    ALLEN              30 NOT Found
    JAMES              30 NOT Found
    BLAKE              30 NOT Found
    MARTIN             30 NOT Found
    michaels>  SELECT   ename, deptno,
             CASE
                WHEN deptno IN (
                       SELECT *
                         FROM (SELECT CASE
                                         WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                            THEN deptno
                                         ELSE 1000
                                      END
                                 FROM dept))
                   THEN 'Found'
                ELSE 'NOT Found'
             END FOUND
        FROM emp
    ORDER BY deptno
    ENAME          DEPTNO FOUND   
    CLARK              10 Found   
    KING               10 Found   
    MILLER             10 Found   
    JONES              20 Found   
    FORD               20 Found   
    ADAMS              20 Found   
    SMITH              20 Found   
    SCOTT              20 Found   
    WARD               30 NOT Found
    TURNER             30 NOT Found
    ALLEN              30 NOT Found
    JAMES              30 NOT Found
    BLAKE              30 NOT Found
    MARTIN             30 NOT FoundSo in the first query ROW_NUMBER() evaluates to NULL (not sure why) so the condition will never be satisfied! This is easily proofed when actually testing for nullity:
    WHEN ROWNUM() OVER (ORDER BY NULL) IS NULL THEN
    ...will always show 'Found'!
    Inlining the subquery »materializes« it, and ROW_NUMBER() gets the desired value.

  • Unable to write more than 10 case statements in an object in designer

    unable to write more than 10 case statements in an object in designer
    XI 3.0 and XI 3.1
    Please let me know, any known issues.

    Hi,
    yes this is the limitation you cant write more that 10 case statments but you can reduce the number of time you use the case in your object.
    For ex:
    If you are writing few conditions on one field then you can add the login in one case only.
    case when SAL between 100 and 1000 then 'lowsal'
            when SAL between 1000 and 2000 then 'medsal'
            when sal between 2000 and 3000 then highsal
    else
    case when ...then ....
    else
    end
    end
    by following the above ex you can solve your problem.
    But if you are writing case statement based on dofferent columns then write 10 case statements and remaining conditions you can add at the report level.
    using if else condition.
    Hope this will help you....
    Cheers,
    Ravichandra

  • Case statement support in CPL XML

    Hello,
    I'm trying to find a way of implementing a case statement based on H.323_ID of the destination in the already existing and working CPL script on VCS X7.1. The problem is, I can't find any guidance anywhere in the Web. Is the case statement supported at all?
    Thanks!

    Kedar Sadekar (guest) wrote:
    : 1) Does Oracle 8i propose to have XML as a new datatype
    Not at this time.
    : 2) Does a document descriptor mean the mapping of the XML
    : elements to certain columns in an Oracle table? Does it have
    : anything to do with the DTD? Will an XML instance be mapped to
    :a single table only or across multiple tables in a master-detail
    : relationship as the heirarchy in the instance gets too complex?
    A Document Descriptor is basicly a mapping between a DTD and the
    tables and columns in the RDBMS. More that one table can be
    mapped to.
    : 3) How will the ConText cartridge be able to identify XML
    : documents? How will the queries be written to enable 'element-
    : level' searching?
    Context, now interMedia Text, does not 'identify' XML documents
    per se, but can index colums with imbedded XML and search the
    contents between specified tags.
    : 4)What is iFS , especially in relation to XML storage?
    Check out http://www.oracle.com/xml/documents/xml_twp/ for a
    complete description.
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • Subquery inside CASE statement

    I am trying to use a subquery within a Case statement with a 'where' condition that binds to the parent query. Like this:
    Select T.idperson , CASE WHEN  T.type = 'C' THEN (SELECT name from Customers where C.idcustomer = T.idperson)
    ELSE
    (SELECT name from Providers where idprovider = T.idperson)
    END Name
    from myTable T This works for me in SQL Server but in ORACLE the subquery does not return any rows, i guess its the binding to parent query part. Any thoughts of another way I could get the result I want?
    Thanks,
    JuanDiego

    Hi, Juandiego,
    If it's not returning any rows, then you must not have any rows in the table.
    If you have any rows in the table, you will either get
    (a) an error, or
    (b) some rows (even if the columns are NULL).
    There is another way to get the results you want.
    I probably wouldn't use scalar sub-queries. I would outer-join all the tables, like this:
    Select  T.idperson
    ,       CASE
                WHEN  T.type = 'C'
                THEN  c.name
                ELSE  p.name
            END  AS Name
    from             myTable   t
    LEFT OUTER JOIN  Customers c  ON c.idcustomer = T.idperson
    LEFT OUTER JOIN  Providers p  ON p.idprovider = T.idperson
    ;

  • Evaluation of condition clause in whehe clause using case statement

    Hi,
    I have a scenario where in I have to evaluate two different conditions based on the parameter value. Is it possible to evaluate the conditiond based on the parameter value with case statement in where clause.
    Example:
    select A,B,C,D from X,Y,Z
    where
    cond1 and
    cond2 and
    case when param='T' then cond3 else cond4 end
    Here param is an external parameter passed to the query.
    cond3 is something like Y.deptno in(10,30,50,70)
    cond4 is something like Y.deptno in (20,40,60,70,80,90)
    Your responce will be appriciated.
    Regards,
    Varma

    You can place the case statement as a condition, however it depends what context you want it in, for example;
    this will work:
    1* select 1 from dual where (case when 1=1 then 1 end) = 1 and 2=2
    QL> /
            1
            1but this will not;
    SQL> select 1 from dual where case when 1=1 then 1 end and 2=2;
    select 1 from dual where case when 1=1 then 1 end and 2=2
    ERROR at line 1:
    ORA-00920: invalid relational operatorSo, if you're expecting the condition to evaluate to a true/false, so if you mean soemthing like
    when TRUE, then it won't work!
    P;

  • CASE Statement in Where Condition with Multi Valued parameter in SSRS

    Hi All,
    I am little confused while using CASE statement in Where condition in SSRS. Below is my scenario:
    SELECT
    Logic here
    WHERE
    Date IN (@Date)AND
    (CASE
    WHEN NAME LIKE 'ABC%' THEN 'GROUP1'
    WHEN ID IN ('123456', '823423','74233784') THEN 'GROUP2'
    WHEN ABC_ID IS NULL THEN 'GROUP3'
    ELSE 'GROUP4'
    END ) IN (@GROUP)
    So above query uses WHERE condition with CASE statement from @GROUP parameter. I want to pass this parameter as multi- valued parameter and hence I have used CASE statement IN (@GROUP).
    For @Date one dataset will pass the available and default values and
    for @GROUP parameters, another dataset will pass the available and default values.
    But this is not working as expected. Please suggest me where I am making mistake in the query.
    Maruthu | http://sharepoint-works.blogspot.com

    Hi Maruthu,
    According to your description, I create a sample report in my local environment. It works as I expected. In your scenario, if the selected values from the Date parameter contains some of the Date field values, the selected values from the GROUP parameter
    contains some of GROUPS (‘GROUP1’,’GROUP2’,’GROUP3’,’GROUP4’) and the corresponding when statement is executed , then the dataset returns the corresponding values.
    In order to trouble shoot this issue, could you tell us what results are you get and what’s your desired results? If possible, you can post the sample data with sample dataset, then we can make further analysis and help you out.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Is it possible to use a case statement when joining different tables based on input parameters?

    Hi,
    I have a scenario where my stored procedure takes 5 parameters and the users can pass NULL or some value to these parameters and based on the parameters, I need to pull data from various tables.
    Is it possible to use a case statement in the join, similar the one in the below example. I'm getting error when I use the below type of statement.
    select a.*
    from a
    case
    when parameter1=1 then
    inner join a on a.id = b.id
    when parameter1=2 then
    inner join a on a.id = c.id
    end;
    Please let me know, if this type of statement works, and if it works will it create any performance issues?. If the above doesn't work, could you please give me some alternate solutions?
    Thanks.

    Here's a technique for joining A to B or C depending on the input parameters. In theory, you are joining to both tables but the execution plan includes filters to skip whichever join is not appropriate. The drawback is that you have to do outer joins, not inner ones.
    CREATE TABLE A AS SELECT LEVEL ak FROM dual CONNECT BY LEVEL <= 100;
    CREATE TABLE b AS SELECT ak, bk
    FROM A, (SELECT LEVEL bk FROM dual CONNECT BY LEVEL <= 10);
    CREATE TABLE c(ak, ck) AS SELECT ak, bk*10 FROM b;
    variable p1 NUMBER;
    variable p2 NUMBER;
    exec :p1 := 1;
    exec :p2 := 20;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.01 |       7 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       7 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |
    |*  5 |     FILTER            |                 |      1 |        |      9 |00:00:00.01 |       4 |
    |*  6 |      TABLE ACCESS FULL| B               |      1 |      9 |      9 |00:00:00.01 |       4 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |
    |*  8 |    FILTER             |                 |      1 |        |      0 |00:00:00.01 |       0 |
    |*  9 |     TABLE ACCESS FULL | C               |      0 |      9 |      0 |00:00:00.01 |       0 |
    Predicate Information (identified by operation id):
       1 - access("A"."AK"="ITEM_0")
       2 - access("A"."AK"="ITEM_1")
       3 - filter("A"."AK"<=9)
      5 - filter(:P1 IS NOT NULL)
       6 - filter(("B"."AK"<=9 AND "B"."BK"=:P1))
       8 - filter((:P2 IS NOT NULL AND :P1 IS NULL))
       9 - filter(("C"."AK"<=9 AND "C"."CK"=:P2))
    You can see that table C was not really accessed: the buffer count is 0.
    exec :p1 := NULL;
    SELECT /*+ gather_plan_statistics */ A.ak, nvl(b.bk, c.ck) otherk FROM A
    LEFT JOIN b ON A.ak = b.ak AND :p1 IS NOT NULL AND b.bk = :p1
    LEFT JOIN c ON A.ak = c.ak AND :p1 is null and :p2 IS NOT NULL and c.ck = :p2
    WHERE A.ak <= 9;
    SELECT * FROM TABLE(dbms_xplan.display_cursor(NULL,NULL,'IOSTATS LAST'));
    Now table B is not accessed.
    | Id  | Operation             | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
    |   0 | SELECT STATEMENT      |                 |      1 |        |      9 |00:00:00.02 |       7 |      2 |
    |*  1 |  HASH JOIN OUTER      |                 |      1 |      9 |      9 |00:00:00.02 |       7 |      2 |
    |*  2 |   HASH JOIN OUTER     |                 |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |*  3 |    TABLE ACCESS FULL  | A               |      1 |      9 |      9 |00:00:00.01 |       3 |      0 |
    |   4 |    VIEW               | VW_DCL_5532A50F |      1 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |*  5 |     FILTER            |                 |      1 |        |      0 |00:00:00.01 |       0 |      0 |
    |*  6 |      TABLE ACCESS FULL| B               |      0 |      9 |      0 |00:00:00.01 |       0 |      0 |
    |   7 |   VIEW                | VW_DCL_5532A50F |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |
    |*  8 |    FILTER             |                 |      1 |        |      9 |00:00:00.01 |       4 |      2 |
    |*  9 |     TABLE ACCESS FULL | C               |      1 |      9 |      9 |00:00:00.01 |       4 |      2 |

  • How to manipulate arrays using case statements and boolean conditions?

    In the vi that is attached I am trying to compare two values in two different arrays and delete the value that is equal to zero.  The values of each array are rounded to the closest integer.  Then I attempted to apply the ">0" boolean as the condition for my case statement, but I am getting an error.  Any tips on manipulating arrays with case statements?
    Attachments:
    Patient Movement Monitoring.vi ‏141 KB

    Thank you!!! that was a huge help. I don't think I need the case structures at all.  The next part of the code compares the 4 values in the array. 
    If columns 0 and 1 are both positive -> output 1
    If column 0 is negative and 1 is positive -> output 2
    If columns 0 and 1 are both negative -> output 3
    If column 0 is positive and 1 is negative -> output 4
    (0 is x-axis value, 1 is y-axis value.....outputs are assigning quadrants to the combination)
    Only one of the "AND" booleans will return true for each index.  Is there a way to initialize another array of outputs 1-4 depending on which AND returns true?
    Attachments:
    Patient Movement Monitoring.vi ‏144 KB

  • Conditional Filters using case statements

    Hello,
    I have a table view which displays Total Quota and Theatre Quota. Against the Total Quota, there are 2 values - Rollover Revenue and Theatre Revenue. Against the Theatre Quota, there is only Theatre Revenue.
    What I want to accomplish is to display only the Rollover Revenue Aggregated Quarterly number whenever there is a Total Quota number and not display the Theatre Revenue number
    In the table view,
    Year Name     Quarter Name     Quarter Name Sort     Person Region     Quota Name     Quarterly Quota     Credit Amount     QTD Attainment     Credit Type Name
    YEAR-2012     QTR-1-2012     QTR-1-2012     750     Total Quota     6,128,500     5,492,081     89.62%     Rollover Revenue Aggregated Quarterly
                   750          6,128,500     5,344,000     87.20%     Theatre Revenue
         QTR-2-2012     QTR-2-2012     750     Total Quota     5,922,500     5,890,264     99.46%     Rollover Revenue Aggregated Quarterly
                   750          5,922,500     6,120,000     103.33%     Theatre Revenue
         QTR-3-2012     QTR-3-2012     750     Total Quota     5,716,500     0     0.00%     
         QTR-4-2012     QTR-4-2012     750     Total Quota     5,510,500     0     0.00%     
    I used an example in the following link:
    http://oraclebizint.wordpress.com/2008/02/06/oracle-bi-ee-101332-conditional-filters-using-case-statements-in-filters/
    and applied the example in my scenario:
    CASE WHEN Quota."Quota Name" = 'Total Quota' THEN "Credit Type"."Credit Type Name" ELSE 'Dummy' END != 'Theatre Revenue'
    I still get duplicate rows.
    Thanks.

    Could you suggest any solutions for this problem where I can conditionally hide the number only for a certain type of data and not for all type of data?
    Thanks.

  • Checking for the condition types using case statement

    hi folks,
    I have a lot of condition types that I have to check for and I am using case statement to do that. The code goes like this.
    case wac-kschl.
            when 'ZRAT' OR 'ZAGR' OR 'ZRCR' OR
                  'Y098' OR 'Y007' OR 'ZREW' OR 'Y106'        OR 'ZTSR' OR 'Y127' OR 'Y125' OR 'Y126' OR 'Y124' OR 'Y157' OR 'Y092' OR 'Y085' OR 'Y090' OR 'ZMZD'
    OR 'Y215' OR 'Y214' OR 'Y111' OR 'ZC$D' OR 'ZAUD'.
    up till here it is working on errors and when I add few more condition types to the case statement it is throwing the error.
    I have to check for all the condition types out here.
    How can I correct it? Is there a better way to do it?
    thanks
    Santhosh

    Hi Santhosh,
    I think that your CASE statement has a flaw. The line length of one of the lines is too large. You need to insert a carriage-return to shorten it (or press the button 'Pretty Printer').
    The code would look nicer like this:[code]  CASE wac-kschl.
        WHEN 'ZRAT' OR 'ZAGR' OR 'ZRCR' OR 'Y098' OR 'Y007' OR 'ZREW'
          OR 'Y106' OR 'ZTSR' OR 'Y127' OR 'Y125' OR 'Y126' OR 'Y124'
          OR 'Y157' OR 'Y092' OR 'Y085' OR 'Y090' OR 'ZMZD' OR 'Y215'
          OR 'Y214' OR 'Y111' OR 'ZC$D' OR 'ZAUD' OR 'Z001' OR 'Z002'
          OR 'Z003' OR 'Z004' OR 'Z005' OR 'Z006' OR 'Z007' OR 'Z008'
          OR 'Z009' OR 'Z010' OR 'Z011' OR 'Z012' OR 'Z013' OR 'Z014'.
        Do your thing here
          WRITE: / 'OK'.
        WHEN OTHERS.
          WRITE: / 'NOT OK'.
      ENDCASE.[/code]If this will not work for you, you could try a different approach:[code]* Local definition
      DATA:
        var_list(1024).
    Build variable string for checking
      CONCATENATE 'ZRAT ZAGR ZRCR Y098'
                  'Y007 ZREW Y106 ZTSR'
                  'Y127 Y125 Y126 Y124'
                  'Y157 Y092 Y085 Y090'
                  'ZMZD Y215 Y214 Y111'
                  'ZC$D ZAUD'
             INTO var_list
        SEPARATED BY space.
    Check if the correct value is supplied
      IF var_list CS wac-kschl.
      Do your thing here
        WRITE: / 'OK'.
      ENDIF.[/code]Hope this helps you a bit.
    Regards,
    Rob.

  • Case statement for dashboard text title based on NQ_SESSION.ROLES

    Hello,
    I figured out on my dashboard I can add a textbox
    with the code '@{biserver.variables['NQ_SESSION.ROLES']}'  and it shows the user groups. That works great. Now
    I need to have a case statement or so that shows a text, that changes
    with each user role i.e. each user role gets its own "report title" Is that possible?
    Thanks.

    Hello,
    Thanks for the column formula example.
    Unfortunately in both cases it resolves to the ELSE clause even when the other two are true:
    case  when Locate('BIConsumer_Two', VALUEOF(NQ_SESSION.ROLES))>0 then @{VAR_REPORTTITLE}{'test'} when Locate('BIConsumer_One', VALUEOF(NQ_SESSION.ROLES))>0 then @{VAR_REPORTTITLE}{'test2'}   else @{VAR_REPORTTITLE}{'test3'}   end  
    case when Position('userrole1' in VALUEOF(NQ_SESSION.ROLES))>0 then 'w00t' else 'ang' end
    The one below works (at least I can read test1 on the results page of my answers report:
    case when Position('mytestrole' in 'mytestrole')>0 then @{VAR_REPORTTITLE}{'test1'} else @{VAR_REPORTTITLE}{'test'} end
    The NQ_SESSION.ROLES comes like this:
    'BIConsumer_One;BIAdministrator;AuthenticatedUser;BIConsumer;BIConsumer_Two;BIAuthor'
    I realized why I could not resolve it. I did not define it as a session but presentation variable. So here it is a session variable:
    case when Position('mytestrole' in 'mytestrole')>0 then VALUEOF(NQ_SESSION.VAR_REPORTTITLE) ='test1' else VALUEOF(NQ_SESSION.VAR_REPORTTITLE)='test2' end
    but now there is an error: [nQSError: 26012]

  • Conditional case statement help.!

    Hello Forum Members,
    I have a table with stores order along with order dates and other information. I have a requirement to write a query to get the nominations from that order's table according to the logic mentioned below.
    Nom1 =  Initial order date and next order within 7 days from initial order date then its considered as R1
    Nom2 = next activity within 7 seven on the same ord_id from its R1 date , this goes on as the order dates increases for same  or single ord_no
    Final Rn  is Count (Rn)
    Rn %-- Count(Rn)  / Count Distinct ( ord_no ) * 100
    Example data output:
    ORD_DATE
    ORD_ID
    1_of_x
    2_of_x
    3_of_x
    4_of_x
    5_of_x
    6_of_x
    Final RnX
    Rn%
    7/10/2013
    10095V1
    1
    0
    0
    0
    0
    0
    8/3/2013
    10095V1
    1
    0
    0
    0
    0
    0
    8/8/2013
    10095V1
    0
    1
    0
    0
    0
    0
    8/12/2013
    10095V1
    0
    0
    1
    0
    0
    0
    9/6/2013
    10095V1
    1
    0
    0
    0
    0
    0
    DDL:
    create table xx_ord_noms
    ord_no varchar(30),
    ord_date date,
    ord_id varchar2(30)
    Sample Data:
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('07/10/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/03/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/08/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/12/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('09/06/2013','MM/DD/YYYY'), '10091');
    commit;
    I was planning to doing something like this but I am not getting the logic for R1 .. R7
    select ord_no,
           ord_date,
           ord_id,
           prev_dt,
           (to_date(ord_date) - to_date(prev_dt)) data_diff,
           case
             when prev_dt is null or
                  (to_date(ord_date) - to_date(prev_dt)) < 7 then
              'R1'
             when (to_date(ord_date) - to_date(prev_dt)) > 7 THEN
              'R2'
             ELSE
              nULL
           END
      FROM (select a.*,
                   (SELECT MAX(tmp2.ord_date)
                      FROM xx_ord_noms tmp2
                     WHERE a.ord_id = tmp2.ord_id
                       AND tmp2.ord_date < a.ord_date) prev_dt
              from xx_ord_noms a);
    Could someone give me advises or suggestions on how we can get the expected output.
    Thanks in advance.

    LAG and LEAD are good when you want to look forward or back a fixed number of rows, but in this case you don't know how far back you'll need to go.
    I've got a solution. it calculates the Rn as a number, not a column position, but you can transform that with CASE statements if you want. I did it in two main steps:
    First I calculated the Rn by comparing the date of the current and previous row. To do that, I generated a row number using the row_number()  analytic function:
    select ord_no,
           ord_date,
           ord_id,
           numrow
    , Rn
    from xx_ord_noms
    model
      partition by (ord_no)
      dimension by (row_number() over (partition by ord_no order by ord_date)  numrow)
      measures (ord_date, 0 Rn, ord_id )
      rules update
        rn[1] = 1,
        rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1])  < 7 then rn[cv()-1]+1 else 1 end
    ORD_NO     ORD_DATE             ORD_ID         NUMROW         RN
    10091      10-Jul-2013 00:00:00 10091               1          1
    10091      03-Aug-2013 00:00:00 10091               2          1
    10091      08-Aug-2013 00:00:00 10091               3          2
    10091      12-Aug-2013 00:00:00 10091               4          3
    10091      06-Sep-2013 00:00:00 10091               5          1
    Then I needed to identify all the rows of each series. I defined firstDt as the date of the first item in the series:
    firstDt[1] = ord_date[cv()]
    firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
    With that, the FinalRn is just an analytic max(rn) over (partition by firstDt)
    I'm not clear on what R% is. Your descriptions are unclear and I think they're inconsistent.
    select ord_no, ord_date, ord_id
    , Rn, finalRn, 100*finalRn/totCnt PCT1, 100 * totRn/totCnt PCT2
    , totRn
    from xx_ord_noms
    model
      partition by (ord_no)
      dimension by (row_number() over (partition by ord_no order by ord_date)  numrow)
      measures (ord_date, 0 Rn, ord_id, to_date(null) firstDt, 0 finalRn, 0 totRn, 0 totCnt )
      rules upsert all
        rn[1] = 1
      , rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1])  < 7 then rn[cv()-1]+1 else 1 end
      , firstDt[1] = ord_date[cv()]
      , firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
      , finalRn[ANY] = max(rn) over (partition by firstDt)
      , totCnt[ANY] = count(*) over()
      , totRn[ANY] = count(case when rn = 1 then 1 else null end) over ()
    ORD_NO     ORD_DATE             ORD_ID             RN    FINALRN       PCT1       PCT2      TOTRN
    10091      10-Jul-2013 00:00:00 10091               1          1         20         60          3
    10091      03-Aug-2013 00:00:00 10091               1          3         60         60          3
    10091      08-Aug-2013 00:00:00 10091               2          3         60         60          3
    10091      12-Aug-2013 00:00:00 10091               3          3         60         60          3
    10091      06-Sep-2013 00:00:00 10091               1          1         20         60          3
    Regards,
    David

  • Using a scalar user defined function in a select case statement

    I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
    ZIPCODE' below.
    SELECT
        CASE
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             ELSE NULL
           END as Zipcode,
    FROM
    table1

    SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
      FROM table1
    Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
       CASE WHEN a IS NOT NULL THEN a
            WHEN b IS NOT NULL THEN b
            WHEN c IS NOT NULL THEN c
       END
    But if you use isnull it's a different matter. (But isnull() permits two arguments.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem In Case Statement

    HI ALL,
    in the program,i need to display description based on condition type.
    so we used CASE statement as below in LOOP. ITS not working .
    could anyone please suggest if anything wrong in the following code.
    LOOP AT gt_mat.
           MOVE gt_mat-type  TO gt_final-type.
      Condition description
    CASE gt_mat-type  .
    when  'N'.
    move  'New'  to gt_final-condes.
    when  'B'.
    move 'Block'   to gt_final4-condes.
    ENDCASE.
    ENDLOOP.
    please let me know whats the problem i above code and how to solve.
    thanks in advance.

    Hi,
    The only solution for this could be to debug the program and check if the coresponding values are populated and available. You could also try to replace the CASE statement with a simple IF statement and check if its working.
    LOOP AT gt_mat.
    MOVE gt_mat-type TO gt_final-type.
    * Condition description
    IF gt_mat-type = 'N'.
    gt_final-condes = 'New'.
    elseif gt_mat-type = 'B'.
    gt_final-condes ='Block'.
    append gt_final.
    clear gt_final.
    ENDIF.
    ENDLOOP.
    Also make sure the case of the value in gt_mat-type matches with the condition
    Regards,
    Vikranth

Maybe you are looking for