SQL Case statement Help....

Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
I have got that with the below SQL:
Count of Overrides =
select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
But now i have to look at two columns and get the count()
I have
col_1 and col_2 in table_1 and
col_3 and col_4 in table_2
(I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
Will the following SQL return correct values?
Count of Overrides =
Select
Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
Thanks

"yes, it can be rewritten as a decode. but why bother?"
Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
SQL> WITH t AS (
  2     SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
  3     SELECT 1, 1, 2, 3 FROM dual UNION ALL
  4     SELECT 1, 2, 3, 3 FROM dual UNION ALL
  5     SELECT null, 1, 2, 2 FROM dual UNION ALL
  6     SELECT 1, 1, 2, null FROM dual UNION ALL
  7     SELECT 1, 2, 3, 4 FROM dual)
  8  SELECT col_1, col_2, col_3, col_4,
  9         CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
10         DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
11  FROM t;
     COL_1      COL_2      COL_3      COL_4      OCASE O
         1          1          2          2
         1          1          2          3          1 1
         1          2          3          3          1 1
                    1          2          2            1
         1          1          2                       1
         1          2          3          4          1 1John

Similar Messages

  • SQL CASE statement in XML template- End tag does not match start tag 'group

    Hi All,
    I am developing a report that has the SQL CASE statement in the query. I am trying to load this into RTF with report wizard and it gives me below error
    oracle.xml.parser.v2.XMLParseException: End tag does not match start tag 'group'
    Does XML publisher support CASE statement?
    My query is something like this
    SELECT customercode,
    SUM(CASE WHEN invoicedate >= current date - 30 days
    THEN balanceforward ELSE 0 END) AS "0-30",
    SUM(CASE WHEN invoicedate BETWEEN current date - 60 days
    AND current date - 31 days
    THEN balanceforward ELSE 0 END) AS "31-60",
    SUM(CASE WHEN invoicedate < current date - 60 days
    THEN balanceforward ELSE 0 END) AS "61>",
    SUM(balanceforward) AS total_outstanding
    FROM MyTable
    GROUP BY customercode
    ORDER BY total_outstanding DESC
    Please advice if the CASE statement or the double quotes are causing this error
    Thanks,
    PP

    I got this to work in the XML but the data is returning zeros for all the case statements. When I run this in toad I get results for all the case conditions but when ran in XML the data displayed is all zeros. I am not sure what I am missing. Can someone shed some light on this please
    Thanks!
    PP

  • T-sql case statement in a select

    When I execute the following t-sql 2012 statement, the "NO Prod' value is not
    being displayed from the sql listed below:
    SELECT DISTINCT
    IsNull(cs.TYPE,'') as type,
    CASE IsNull(Course.TYPE,'')
    WHEN 'AP' then 'AP Prod'
    WHEN 'IB' then 'IB Prod'
    WHEN 'HR' then 'HR Prod'
    WHEN '' then 'NO Prod'
    END AS label
    FROM CustSection cs
    INNER JOIN dbo.Person p on P.personID = cs.personID
    Left join customCustomer cs564 on cs564.personID = p.personID and
    cs564.attributeID ='564'
       where ( cs.type is null and cs564.attributeID = null)    
         or
        (cs.type IN ('HR','AP') OR
          (cs.type='IB' AND SUBSTRING(cs.code,1,1)='3'))  
    ORDER BY label
    What I want is for 'NO Prod' to be displayed when
    cs.type is null and cs564.attributeId  is null.
    Thus can you tell me how to fix query above so the 'NO Prod'  value is displayed in the
    select statement listed above?

    There is no CASE statement in SQL; we have a CASE expression. We do not use the old 1970's Sybase*- ISNULL(); we have  COALESCE().
    There is no such thing as a magic generic “type” in RDBMS. There is no such thing as a generic “code” in RDBMS. They have to to be “<something in particular>_type” and “<something in particular>_code” in a valid data model. How about blood_type
    and postal_code?? 
    There is no such thing as a generic “person” table in RDBMS. First of all, do you really have only one person, as you said?? But the important point is that these persons play a role in the data model – customers, students, etc. You are doing the wrong thing
    and doing it badly.  This table should not exist any more than a  table of “Things” such exist. 
    And the reason you are beyond any real help is “attribute_id” which tell us that your schema is a total disaster of data and meta data mixed together in a non-RDBMS written in awful SQL. Based on cleaning up bad SQL for 30 years, it looks like you are an OO
    programmer who never unlearned his prior mindset. 
    Why did you allow an encoding schema with blanks? Why do you have so many NULL-able columns? 
    SELECT DISTINCT is very rare in a properly designed schema. The DRI references assure that rows cam be matched. To get you started, look at this skeleton:
    CREATE TABLE Products
    (product_gtin CHAR(15) NOT NULL PRIMARY KEY, 
     product_type CHAR(2) DEFAULT 'XX' NOT NULL
      CHECK (product_type IN ('AP', 'IB', 'HR', 'XX'))
    The table name is a plural noun because it models a set (NOT an OO class).
    The GTIN is an industry standard identifiers, and not have to invent our own.
    The product_type (not blood_type, not automobile_body_type!) has a constraint that assures it is never NULL and never blank; I invented 'XX' as a default. 
    You need more help than you can get in a forum, but if you will follow Netiquette and post the DDL, we can get you started.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Case Statement Help needed

    case
    when datepart(mm,[SDate]) between '9' and '11' and datepart(mm,[PDate] ) between '9' and '11'
    Then 'Q1_'
    when datepart(mm,[SDate]) between '12' and '02' and datepart(mm,[PDate] ) between '12' and '02'
    Then 'Q2_'
    when datepart(mm,[SDate]) between '03' and '05' and datepart(mm,[PDate] ) between '03' and '05'
    Then 'Q3_'
    when datepart(mm,[SDate]) between '06' and '08' and datepart(mm,[PDate] ) between '06' and '08'
    Then 'Q4_'
    else 'N/A' end as QTR
    from DDA_2015_FSR
    Datatype for SDate and Pdate
    2014-09-01 00:00:00
    I need help with above case statement, When I run the case statement I get 'N/A FSY_2015   ' When I add the following where clause to validate the results. In my table I do have records for all four quarters, Except Q1, all other rows I get  'N/A
    FSY_2015   '
    Am i missing something? Can someone help me here?
    where
    datepart(m,[SDate]) 
    between
    '12'
    and
    '02'
    and  
    datepart(m,[PDate]
    between
    '12'
    and
    '02'
    FM

    There is no CASE statement in SQL; it is a CASE expression. Big difference. 
    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
    The report period table gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Something_Report_Periods
    (something_report_name CHAR(10) NOT NULL PRIMARY KEY
       CHECK (something_report_name LIKE <pattern>),
     something_report_start_date DATE NOT NULL,
     something_report_end_date DATE NOT NULL,
      CONSTRAINT date_ordering
        CHECK (something_report_start_date <= something_report_end_date),
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • SQL Case Statement

    Hi,
    could you please advise how to add below New case to below Main case
    New case:
    when (convert(varchar,date,101) >= '01/01/2014' OR qtr >= '14Q1') then
    case when PP='ABC' and pl='EFG' then Revenue*.552
    else 0 end
    Main case:
    SUM(
    case
    when ((convert(varchar,date,101)>= '09/19/2013' and qtr = '13Q3') OR qtr >= '13Q4') then
    case when PP='ABC' and pl='EFG' then Revenue*.542
    else 0 end
    when (convert(varchar,date,101) < '09/19/2013' OR qtr < '13Q3') then
    case when PP='ABC' and pl='EFG' then Revenue*.501
    else 0 end
    else 0 end) revenue,

    There is no CASE statement in SQL; we have CASE expression. AND you got the syntax wrong. SQL uses the ISO-8601 date format; it is one of the most basic ISO Standards on Earth AND you should know it. But worse than that, you are still using the 1970's
    Sybase CONVERT string function! NO! Did you know that DATE is a reserved word in SQL AND cannot be a column name? 
    When we design a code for temporal units like Quarters, we follow the ISO-8601 as closely as possible. That means a full four-digit year. 
    Since you were rude AND did post DDL, I will guess that your improper “date” is a TIMESTAMP (aka DATETIME or DATETIME2(n) in Microsoft dialect). 
    >> could you please advise how to add below New CASE to below Main CASE <<
    I never heard the term “main CASE”, even when I voted on this feature. Can you explain it to me and show where I missed it? 
    The quarters are temporal computations; we would not put them in a base table, but a good SQL programmer would use a VIEW with a join to a report period table.   
    CASE WHEN CAST (foobar_timestamp AS DATE) >= '2014-01-01'
           OR foobar_qtr > = '2014Q1'
         THEN CASE WHEN pp = 'ABC' 
                   AND pl = 'EFG'
              THEN something_revenue * 0.552
              ELSE 0.000 END;
    I will assume that pl and pp well-understood terms in your industry and not improper data element names. Why did you nest CASE expressions? Let me answer that: you think that CASE is IF-THEN-ELSE statements! 
    Did you notice that an event during '2014Q1' is always BETWEEN '2014-01-01' AND '2014-03-31'? So this is redundant! 
    A minor point, it is good idea to use a leading zeroes and decimal zeroes to show the guy maintaining code what he is working with. It also helps the compiler avoid casting. Your expression also has no name. 
    CASE WHEN CAST (foobar_timestamp AS DATE) > = '2014-01-01'
     AND pp = 'ABC' 
     AND pl = 'EFG'
     THEN something_revenue * 0.552
     ELSE 0.00 END AS nameless_floob;
    I am afraid that you might have re-discovered the Algol-60 dangling ELSE problem. As with Algol-60, the ELSE in SQL associates with the nearest CASE. Not with the outermost CASE. 
    Your expression ought to have this skeleton: 
    SUM(CASE WHEN ??? 
             THEN something_revenue * 0.542
             WHEN ??? 
             THEN something_revenue * 0.501
             WHEN ???
             THEN something_revenue * 0.552
             ELSE 0.000 END)
     AS something_revenue_tot
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • 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

  • Can CR 2008 with XML ODBC driver using SQL CASE statement?

    Hi:
    when i use SQL Command to provide data to the report from XML file connection. I can not use CASE statement , CR always has error message about "CASE" word.
    I test the same Statement in SQL client connected to Oracle, it runs fine.
    So.. Is it driver's limitation that XML datasource can not use CASE statement inside SQL command window?
    Thanks anyone's reply in advance.
    Johnnychi

    Hi Johnny,
    CR supports what every the ODBC driver supports. The error you are getting is from the XML driver, CR is just passing it through.
    Try using an ODBC to XML driver and then a stand-alone ODBC test tool to see if your SQL works.
    If not you'll have to find another way to use the CASE statement.
    Thank you
    Don

  • PL/SQL - Case Statement

    Hello, just starting to learn PL/SQL. I have a query which runs just fine and it has a case statement. When I take that query and place it into a procedure and compile, it gives me a compile error stating "ENCOUNTERED symbol CASE when expecting... providing a list of symbols.
    This procedure is part of a package, so I am only showing the procedure portion...
    PROCEDURE QRY_USERS (oRows                     OUT t_cursor)
    IS
    BEGIN
         OPEN o_Rows FOR
         select ou.User_id,
                   ou.AD_Login_ID,
                   ou.First_name,
                   ou.Last_Name,
         oct.CODE_DESC,
                   case when ou.deleted is null then 'N'
                   else 'Y' end Deleted
         from tst_ops_users ou, tst_ops_code_tbl oct
         where oct.CODE_TYPE ='USER_TYPE'
              and oct.code_name = ou.USER_ROLE_TYPE;
    END QRY_USERS;
    So is there some different syntax with case statements or is there some other erro causing this?
    Thanks a bunch for your assistance!!!

    Which version of the database are you working on? In 8i the PL/SQL engine did not support the use of CASE in SQL statements (along with a whole bunch of other fresh additions to SQL syntax).
    If that is your problem you could try this, which ought to use the SQL engine instead...
    PROCEDURE QRY_USERS (oRows OUT t_cursor)
    IS
    BEGIN
    OPEN oRows FOR
    'select ou.User_id,
    ou.AD_Login_ID,
    ou.First_name,
    ou.Last_Name,
    oct.CODE_DESC,
    case when ou.deleted is null then ''N''
    else ''Y'' end Deleted
    from tst_ops_users ou, tst_ops_code_tbl oct
    where oct.CODE_TYPE =''USER_TYPE''
    and oct.code_name = ou.USER_ROLE_TYPE';
    END QRY_USERS;although you can obviate the need for CASE by using either DECODE or NVL2...
    nvl2(ou.deleted , 'Y', 'N') AS deletedCheers, APC

  • Switch Case Statement Help...

    Hello,
    I am trying to get my pages through Case Statement But...
    Can any one Help me.. here is my code..
    This is my Buttons Code... My buttons are on 1st Frame of My FLA..
    stop();
    btn1.addEventListener(MouseEvent.CLICK, varTest);
    btn2.addEventListener(MouseEvent.CLICK, varTest2);
    function varTest(event:MouseEvent):void
         var page = 1;
         gotoAndStop(20);
    function varTest2(event:MouseEvent):void
         var page = 2;
         gotoAndStop(20);
    and this is my 20th frame code. (here I'm checking variable)
    import flash.events.Event;
    addEventListener(Event.ENTER_FRAME,checkCaseMe);
    function checkCaseMe(event:Event)
         switch (page)
              case "1" :
                   info_txt.text = "page1";
                   break;
              case "2" :
                   info_txt.text = "page1";
                   break;
              default :
                   info_txt.text = "page00";
    When I test the movie.. Error Occured (Scene 1, Layer 'Actions', Frame 21, Line 6 1120: Access of undefined property page. )
    Can Anyone help please.. How do I correct this....???
    Thanks...

    You should learn to use the trace() function to help you troubleshoot code yourself.  In each of your button functions include:
    trace("btn clicked"); // will help you know for sure that the buttons are working
    And in frame 20, you should add a trace as well to determine whether you actually get there when you think you don't...
    trace("in frame 20");
    Lastly, your code for frame 20 is likely not what you need for a couple of reasons...
    1) If you think the ENTER_FRAME listener is used to detect/trigger when the timeline enters a frame, that is not what it does.  What it does is continually process the function that it calls at the frame rate of the file.  It is normally only used when you want to repeatedly trigger some functionality.
    2)  If you assign number values to the page variable, you do not want to use String values in your cases.
    All you should need in frame 20 is...
    switch (page)
         case 1 :
              info_txt.text = "page1";
              break;
         case 2 :
              info_txt.text = "page1";
              break;
         default :
              info_txt.text = "page00";

  • Case statement help needed bit tricky

    I have a requirement for a Column Quarters which will idenitfy records based on their service and paid paids.
    Output of Column should be
    QTR
    FSY2015Q1
    Our Quarters start like this Q1= 9/1 /2014-11.30.2014 , Q2 12/1/2014 -02/28/2015, Q3: 3/1/2015 - 05/31/2015 Q4:06/01/2015 -08/31/2015.
    With the below Case statement  records that hit Q1 should be for the FSY upcoming.  records  in Sept, Oct, November of 2014, would actually be for FSY15Q1  (not FSY14Q1).   How can i correct
    this ?
    case
    when datepart(mm, Service_Through_Date ) between '9' and '11' and datepart(mm, c.paid_date ) between '9' and '11'
    Then 'Q1 '
    when datepart(mm, Service_Through_Date ) in ('01','02', '12' ) and datepart(mm, paid_date ) in ('01','02' , '12' )
    Then 'Q2 '
    when datepart(mm, Service_Through_Date ) between '03' and '05' and datepart(mm, paid_date ) between '03' and '05'
    Then 'Q3 '
    when datepart(mm, Service_Through_Date ) between '06' and '08' and datepart(mm, paid_date ) between '06' and '08'
    Then 'Q4 '
    else ' ' end + ' ' + 'FSY ' + '' + cast(datepart(Year, Service_Through_Date)as char(7)) as QTR
    FM

    Your best bet here is going to be to create a calendar table, which has your quarters in it.
    I wrote an article on them here: http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx.
    For your particular scenario you'll need to add a column to the existing code, something like this:
    SELECT CASE WHEN DATEPART(MONTH,@date) IN (9,10,11) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q1'
    WHEN DATEPART(MONTH,@date) IN (12) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q2'
    WHEN DATEPART(MONTH,@date) IN (1,2) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q2'
    WHEN DATEPART(MONTH,@date) IN (3,4,5) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q3'
    WHEN DATEPART(MONTH,@date) IN (6,7,8) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q4'
    END AS fiscalQuarterName
    Once you have this column, you can simply join to the calendar table:
    SELECT service_through_date, paid_date, sc.fiscalQuarterName, pc.fiscalQuarterName
    FROM myTable t
    INNER JOIN calendar sc
    ON t.service_through_date = c.today
    INNER JOIN calendar pc
    ON t.paid_date = pc.today
    If you can't, or don't want to impliment this, you could solve the issue in your cast statement by moving the year into the CASE, like this:
    SELECT CASE WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 9 AND 11 AND DATEPART(MONTH, c.paid_date) BETWEEN 9 AND 11 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q1'
    WHEN DATEPART(MONTH, Service_Through_Date ) = 12 AND DATEPART(MONTH, c.paid_date) = 12 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q2'
    WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 1 AND 2 AND DATEPART(MONTH, paid_date) BETWEEN 1 AND 2 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q2'
    WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 3 AND 5 AND DATEPART(MONTH, paid_date) BETWEEN 3 AND 5 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q3'
    WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 6 AND 8 AND DATEPART(MONTH, paid_date) BETWEEN 6 AND 8 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q4'
    ELSE 'FSY'+RIGHT(YEAR(Service_Through_Date),2)
    END
    Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

  • Case Statement Help needed [Nested]

    Hi all,
    I need to write a case statement my requirement is
    ENC.EET.40 E_Disposition populated from either “E_ Status” field of HP_Response_table, “File Status” of HP _TTT_Response_Table,
    or “E_Status” of DDA_R_Table. If no data in any of these fields, default to “Submitted”
     So my case stmt should look like
    case when E_Status is null then 'SUBMITTED'
    when   e_status is null then 'Submitted'
    when    FileStatus is null then 'Submitted'
    Else case when E_status is not null then ............?????????????
    else case when
    Im Confused.. Can someone help me ?
    FM

    select ...
    coalesce (resp.E_Status, resp2.FileStatus, dda.E_Status, 'Submitted')
    from ...
    Obviously I have used alias for the respective tables according to your logic.

  • Formatted search case statement help

    Hi all,
    I am trying to write a case statement in a formatted search, but am running into an error when I add a condition involving the item code. The code works find with the first WHEN statement involving the customer code $[$4.0.0] however, I receive an internal error when I add the second part involving the item code $[$38.1.1] Please advise.
    SELECT
    CASE WHEN $[$4.0.0] = 'C00023'
    THEN 'E002'
    WHEN $[$38.1.1] = 'ItemA'
    THEN 'J002'
    END
    THank you!
    Jane

    Hi Jane,
    Where do you assign this FMS? If it is on the header, the second condition will not work. If it is line level, try change it to $[$38.1.0\].
    Thanks,
    Gordon

  • 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

  • SQL CASE STATEMENT IMPLEMENTATION

    REquirment
    • Add indicator to the end of the files, (position 1051 in both extracts, either have value of Y or N).
    o DUAL COVERAGE (Y/N)
    • Logic to determine indicator values from Member Eligibility Table:
    o For ‘Y’ indicator:
    o When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID = ‘MD11’ (Mean Dual covered member)
    o For ‘N’ indicator:
     When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID <> ‘MD11’
    • Groups included:
    o 100100 (Medicare)
    o 100598 (Medicaid-OHP)
    • Previous syntax
    • select top 20000
    • EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    • RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    • a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    • YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    • S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    • P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    • BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    • b.HIOS_NUMBER,
    • null as PREMIUM_PAID_DATE,
    • null as PREMIUM_PAID_END_DATE,
    • b.APTC,
    • null as 'GracePeriodIndicatorStartDate',
    • null as'GracePeriodIndicatorEndDate',
    • null as'ExchangePlanType'
    • from Extract_602_603_PBH_Extract_Main a
    • left join Extract_602_603_PBH_Extract_HRI b
    • on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    Syntax I am trying to implement(taking forever to execute) Please help correct
    select distinct
    EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    b.HIOS_NUMBER,
    null as PREMIUM_PAID_DATE,
    null as PREMIUM_PAID_END_DATE,
    b.APTC,
    null as 'GracePeriodIndicatorStartDate',
    null as'GracePeriodIndicatorEndDate',
    null as'ExchangePlanType',
    case when MEPE.CSCS_ID = 'MD11' AND grgr.GRGR_ID IN('100100','100598')
    THEN 'Y'
    ELSE 'N' end as DualCoverageIndicator
    from Extract_602_603_PBH_Extract_Main a
    left join Extract_602_603_PBH_Extract_HRI b
    on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    join FacetsReport.dbo.CMC_MEPE_PRCS_ELIG MEPE
    ON a.CLASS_ID= MEPE.CSCS_ID
    Join FacetsReport.dbo.CMC_GRGR_GROUP grgr
    ON MEPE.GRGR_CK= grgr.GRGR_CK

    >on LEFT(a.MEMBER_NO,7)
    =b.SBSB_ID
    This is not a good JOIN. It is not SARGable:
    http://www.sqlusa.com/bestpractices/sargable/
    Can you post table/index DDL? Thanks.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • SQL Case Statement Problem with Maxdb

    Hello,
    I'm running a J2E application on Netweaver AS. I have on problem that I just cannot figure out.
    The statement works in SQL Studio but when I try to code it it does not work at all.
    select COLA, SUM(CASE WHEN COLB=10 THEN 1 ELSE 0 END) from TABLE group by COLA
    When executed as statement in Java I get:
    Error [javax.servlet.ServletException: java.lang.IllegalStateException: illegal stack size: 4
    contents:
    com.sap.sql.tree.SelectStatement
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.ComparisonPredicate], with root cause [java.lang.Exception: java.lang.IllegalStateException: illegal stack size: 4
    contents:
    com.sap.sql.tree.SelectStatement
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.ComparisonPredicate].
    Any thoughts on that? Thanks!
    Edited by: MD on Feb 18, 2009 7:37 PM

    Hi MD,
    with SQL Studio you mean you work with MaxDB?
    Are you sure you're working directly on MaxDB and not with OpenSQL? (That's different!)
    If you want the first, try setting SQL type "vendor" or "native sql". In such case you have to define a new custom datasource through configuration. How that works depends on the version you are using.
    Try to find out what the actual error message is. The stack trace is not enough. There should be more.
    Regards,
    Benny

Maybe you are looking for