Need help in this query using Case Statement

I have the following query which is currently existing and I am adding few more conditions based on the new requirements which is based on a particular flag set as 1 or 0.
If it is set to 1 then I should use the old query as it is and if it is set to 0 then I should add the new conditions.
Basically when the flag is set to 0, I shouldnt be including some of the records that already exists and should include only new records. This is based on the plan_type_ids in (1,2,3,4).
Hence I am using the Case statement to check if the plan_type_id is in (1,2) then do a set of not exists and if the plan_type_id in (3,4) then do set of not exists.
But when I run this query it is giving me error. What am I doing wrong?
Is there any other simple way to combine all the not exists for all of those select statements as given after the line ------------------------- into a single one?
What am I doing wrong?
I tried putting the NOT EXists before the case too but that too didnt work.
Please help. Appreciate it.
Thank you in advance.
SELECT
ee.employee_id
,'WELCOMEMSG'
,DECODE( me.member_enrollment_id
,first_enr.enrollment_id
,20
,23
) status_id
,me.member_enrollment_id
,wk.welcome_msg_id
FROM wk
,employees ee
,MEMBER_ENROLLMENTS me
,plans pl
,( SELECT employee_id
,plan_type_id
,start_date
,plan_id
,MIN(MEMBER_ENROLLMENT_ID) member_enrollment_id
FROM ( SELECT me.employee_id
,DECODE(pl.plan_type_id,1,2,pl.plan_type_id) plan_type_id
,pl.start_date
,wk.plan_id
,me.member_enrollment_id
FROM wk
,PLANS pl
,MEMBER_ENROLLMENTS me
WHERE wk.done_by = nvl('TEST' ,wk.done_by)
AND wk.welcome_msg_name <> 'NONE'
AND pl.employer_id = wk.employer_id
AND wk.employer_id = 5
AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
AND pl.plan_id = NVL(wk.plan_id,pl.plan_id)
AND me.plan_id = pl.plan_id
AND me.coverage_effective_date <> NVL(me.coverage_end_Date, me.coverage_effective_date + 1)
AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date, me.coverage_effective_date + 1)
MINUS
SELECT me.employee_id
,DECODE(pl.plan_type_id,1,2,pl.plan_type_id) plan_type_id
,pl.start_date
,NULL plan_id
,me.member_enrollment_id
FROM wk
,PLANS pl
,MEMBER_ENROLLMENTS me
WHERE wk.done_by = nvl(NULL,wk.done_by)
AND wk.welcome_msg_name <> 'NONE'
AND pl.employer_id = wk.employer_id
AND wk.employer_id = 5
AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
AND pl.plan_id = wk.plan_id
AND me.plan_id = pl.plan_id
AND me.coverage_effective_date <> NVL(me.coverage_end_Date, me.coverage_effective_date + 1)
AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date, me.coverage_effective_date + 1)
WHERE employee_id = 100
GROUP BY employee_id ,plan_type_id,start_date ,plan_id
)first_enr
,MEMBER_EVENTS mv
WHERE wk.done_by = nvl(NULL,wk.done_by)
AND wk.employer_id = ee.employer_id
AND ee.employee_id = me.employee_id
AND ee.employee_id = 100
AND me.plan_id = pl.plan_id
AND me.coverage_effective_date <> NVL(me.coverage_end_Date, me.coverage_effective_date + 1)
AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date, me.coverage_effective_date + 1)
AND is_expired(me.employee_id,me.plan_id) = 'Y'
AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
AND pl.plan_id=nvl(wk.plan_id,pl.plan_id)
AND me.employee_id = first_enr.employee_id
AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = first_enr.plan_type_id
AND pl.start_date = first_enr.start_date
AND me.member_enrollment_id = mv.member_enrollment_id (+)
AND 'WELCOMEMSG' = mv.event_name(+)
AND mv.member_enrollment_id IS NULL
AND wk.welcome_msg_name <> 'NONE'
AND NVL(first_enr.plan_id,0) = NVL( wk.plan_id,0)
AND (FN_get_all_participant(wk.employer_id) = 1
OR
(FN_get_all_participant(wk.employer_id) = 0
AND (CASE WHEN pl.plan_type_id IN (1,2)
THEN NOT EXISTS (SELECT 'X'
FROM member_accounts ma
member_enrollments men3
plans pl3
plan_types pt3
WHERE ma.member_account_id = men3.member_account_id
AND ma.employee_id = me.employee_id
AND ma.plan_id = pl3.plan_id
AND pl3.start_date < pl.START_DATE
AND TRUNC(men3.coverage_effective_date) <> TRUNC(NVL(men3.coverage_end_date, men3.coverage_effective_date + 1 ))
AND pl3.plan_type_id = pt3.plan_type_id
AND pt3.plan_type_id in (1, 2)
UNION
(SELECT 'X'
FROM member_accounts ma
member_enrollments men3
plans pl3
plan_types pt3
WHERE ma.member_account_id = men3.member_account_id
AND ma.employee_id = me.employee_id
AND ma.plan_id = pl3.plan_id
AND pl3.start_date = (pl.start_date - 365)
\ AND TRUNC(men3.coverage_effective_date) <> TRUNC(NVL(men3.coverage_end_date, men3.coverage_effective_date + 1 ))
AND pl3.plan_type_id = pt3.plan_type_id
AND pt3.plan_type_id = wk.plan_type_id
UNION
(SELECT 'X'
FROM member_accounts ma
member_enrollments men3
plans pl3
plan_types pt3
WHERE ma.member_account_id = men3.member_account_id
AND ma.employee_id = men2.employee_id
AND ma.plan_id = pl3.plan_id
AND pl3.start_date < pl2.START_DATE -- '01-Jan-2011'
AND TRUNC(men3.coverage_effective_date) <> TRUNC(NVL(men3.coverage_end_date, men3.coverage_effective_date + 1 ))
AND pl3.plan_type_id = pt3.plan_type_id
AND pt3.plan_type_id = 2
UNION
(SELECT 'X'
FROM member_accounts ma
member_enrollments men3
plans pl3
plan_types pt3
WHERE ma.member_account_id = men3.member_account_id
AND ma.employee_id = men2.employee_id
AND ma.plan_id = pl3.plan_id
AND pl3.start_date < pl2.START_DATE -- '01-Jan-2011'
AND TRUNC(men3.coverage_effective_date) <> TRUNC(NVL(men3.coverage_end_date, men3.coverage_effective_date + 1 ))
AND pl3.plan_type_id = pt3.plan_type_id
AND pt3.plan_type_id = 1
WHEN pl.plan_type_id IN (3, 4)
THEN NOT EXISTS (SELECT 'X'
FROM member_accounts ma
member_enrollments men3
plans pl3
plan_types pt3
WHERE ma.member_account_id = men3.member_account_id
AND ma.employee_id = men2.employee_id
AND nvl(ma.account_end_date, sysdate) <= trunc(sysdate)
AND ma.plan_id = pl3.plan_id
AND pl3.start_date <= pl2.START_DATE
AND TRUNC(men3.coverage_effective_date) <> TRUNC(NVL(men3.coverage_end_date, men3.coverage_effective_date + 1 ))
AND pl3.plan_type_id = pt3.plan_type_id
AND pt3.plan_type_id in (3, 4)
END
AND (CASE WHEN pl.plan_type_id IN (1,2)
ERROR at line 89:
ORA-00936: missing expression

Maybe
SELECT ee.employee_id,
       'WELCOMEMSG',
       DECODE(me.member_enrollment_id,first_enr.enrollment_id,20,23) status_id,
       me.member_enrollment_id,
       wk.welcome_msg_id
  FROM wk,
       employees ee,
       MEMBER_ENROLLMENTS me,
       plans pl,
       (SELECT employee_id,
               plan_type_id,
               start_date,
               plan_id,
               MIN(MEMBER_ENROLLMENT_ID) member_enrollment_id
          FROM (SELECT me.employee_id,
                       DECODE(pl.plan_type_id,1,2,pl.plan_type_id) plan_type_id,
                       pl.start_date,
                       wk.plan_id,
                       me.member_enrollment_id
                  FROM wk,
                       PLANS pl,
                       MEMBER_ENROLLMENTS me
                 WHERE wk.done_by = nvl('TEST',wk.done_by)  /* same as wk.done_by = 'TEST' */
                   AND wk.welcome_msg_name 'NONE'
                   AND pl.employer_id = wk.employer_id
                   AND wk.employer_id = 5
                   AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
                   AND pl.plan_id = NVL(wk.plan_id,pl.plan_id)
                   AND me.plan_id = pl.plan_id
                   AND me.coverage_effective_date != NVL(me.coverage_end_Date,me.coverage_effective_date + 1)
                   AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date,me.coverage_effective_date + 1)
                MINUS
                SELECT me.employee_id,
                       DECODE(pl.plan_type_id,1,2,pl.plan_type_id) plan_type_id,
                       pl.start_date,
                       NULL plan_id,
                       me.member_enrollment_id
                  FROM wk,
                       PLANS pl,
                       MEMBER_ENROLLMENTS me
                 WHERE wk.done_by = nvl(NULL,wk.done_by)  /* same as 1 = 1 */
                   AND wk.welcome_msg_name 'NONE'
                   AND pl.employer_id = wk.employer_id
                   AND wk.employer_id = 5
                   AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
                   AND pl.plan_id = wk.plan_id
                   AND me.plan_id = pl.plan_id
                   AND me.coverage_effective_date NVL(me.coverage_end_Date,me.coverage_effective_date + 1)
                   AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date, me.coverage_effective_date + 1)
         WHERE employee_id = 100
         GROUP BY employee_id,
                  plan_type_id,
                  start_date,
                  plan_id
       ) first_enr,
       MEMBER_EVENTS mv
WHERE wk.done_by = nvl(NULL,wk.done_by)
   AND wk.employer_id = ee.employer_id
   AND ee.employee_id = me.employee_id
   AND ee.employee_id = 100
   AND me.plan_id = pl.plan_id
   AND me.coverage_effective_date != NVL(me.coverage_end_Date,me.coverage_effective_date + 1)
   AND me.coverage_effective_Date BETWEEN wk.start_date AND NVL(wk.end_date, me.coverage_effective_date + 1)
   AND is_expired(me.employee_id,me.plan_id) = 'Y'
   AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = wk.plan_type_id
   AND pl.plan_id = nvl(wk.plan_id,pl.plan_id)
   AND me.employee_id = first_enr.employee_id
   AND DECODE(pl.plan_type_id,1,2,pl.plan_type_id) = first_enr.plan_type_id
   AND pl.start_date = first_enr.start_date
   AND me.member_enrollment_id = mv.member_enrollment_id(+)
   AND 'WELCOMEMSG' = mv.event_name(+)
   AND mv.member_enrollment_id IS NULL
   AND wk.welcome_msg_name != 'NONE'
   AND NVL(first_enr.plan_id,0) = NVL(wk.plan_id,0)
   AND (
        FN_get_all_participant(wk.employer_id) = 1
    OR
        (FN_get_all_participant(wk.employer_id) = 0
   AND   NOT EXISTS(SELECT 'X'
                      FROM member_accounts ma,
                           member_enrollments men3,
                           plans pl3,
                           plan_types pt3
                     WHERE ma.member_account_id = men3.member_account_id
                       AND ma.employee_id = me.employee_id
                       AND ma.plan_id = pl3.plan_id
                       AND pl3.start_date < pl.START_DATE
                       AND TRUNC(men3.coverage_effective_date) != TRUNC(NVL(men3.coverage_end_date,men3.coverage_effective_date + 1))
                       AND pl3.plan_type_id = pt3.plan_type_id
                       AND pt3.plan_type_id in (1,2)
                       and pl.plan_type_id IN (1,2)
                    UNION
                    SELECT 'X'
                      FROM member_accounts ma,
                           member_enrollments men3,
                           plans pl3,
                           plan_types pt3
                     WHERE ma.member_account_id = men3.member_account_id
                       AND ma.employee_id = me.employee_id
                       AND ma.plan_id = pl3.plan_id
                       AND pl3.start_date = (pl.start_date - 365)
                       AND TRUNC(men3.coverage_effective_date) != TRUNC(NVL(men3.coverage_end_date,men3.coverage_effective_date + 1))
                       AND pl3.plan_type_id = pt3.plan_type_id
                       AND pt3.plan_type_id = wk.plan_type_id
                       and pl.plan_type_id IN (1,2)
                    UNION
                    SELECT 'X'
                      FROM member_accounts ma,
                           member_enrollments men3,
                           plans pl3,
                           plan_types pt3
                     WHERE ma.member_account_id = men3.member_account_id
                       AND ma.employee_id = men2.employee_id
                       AND ma.plan_id = pl3.plan_id
                       AND pl3.start_date < pl2.START_DATE -- '01-Jan-2011'
                       AND TRUNC(men3.coverage_effective_date) != TRUNC(NVL(men3.coverage_end_date,men3.coverage_effective_date + 1))
                       AND pl3.plan_type_id = pt3.plan_type_id
                       AND pt3.plan_type_id = (1,2)
                       and pl.plan_type_id IN (1,2)
                    UNION
                    SELECT 'X'
                      FROM member_accounts ma,
                           member_enrollments men3,
                           plans pl3,
                           plan_types pt3
                     WHERE ma.member_account_id = men3.member_account_id
                       AND ma.employee_id = men2.employee_id
                       AND trunc(nvl(ma.account_end_date,sysdate)) <= trunc(sysdate)
                       AND ma.plan_id = pl3.plan_id
                       AND pl3.start_date <= pl2.START_DATE
                       AND TRUNC(men3.coverage_effective_date) != TRUNC(NVL(men3.coverage_end_date,men3.coverage_effective_date + 1))
                       AND pl3.plan_type_id = pt3.plan_type_id
                       AND pt3.plan_type_id in (3,4)
                       and pl.plan_type_id IN (3,4)
       )Regards
Etbin

Similar Messages

  • Please need help with this query

    Hi !
    Please need help with this query:
    Needs to show (in cases of more than 1 loan offer) the latest create_date one time.
    Meaning, In cases the USER_ID, LOAN_ID, CREATE_DATE are the same need to show only the latest, Thanks!!!
    select distinct a.id,
    create_date,
    a.loanid,
    a.rate,
    a.pays,
    a.gracetime,
    a.emailtosend,
    d.first_name,
    d.last_name,
    a.user_id
    from CLAL_LOANCALC_DET a,
    loan_Calculator b,
    bv_user_profile c,
    bv_mr_user_profile d
    where b.loanid = a.loanid
    and c.NET_USER_NO = a.resp_id
    and d.user_id = c.user_id
    and a.is_partner is null
    and a.create_date between
    TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
    TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
    order by a.create_date

    Perhaps something like this...
    select id, create_date, loanid, rate, pays, gracetime, emailtosend, first_name, last_name, user_id
    from (
          select distinct a.id,
                          create_date,
                          a.loanid,
                          a.rate,
                          a.pays,
                          a.gracetime,
                          a.emailtosend,
                          d.first_name,
                          d.last_name,
                          a.user_id,
                          max(create_date) over (partition by a.user_id, a.loadid) as max_create_date
          from CLAL_LOANCALC_DET a,
               loan_Calculator b,
               bv_user_profile c,
               bv_mr_user_profile d
          where b.loanid = a.loanid
          and   c.NET_USER_NO = a.resp_id
          and   d.user_id = c.user_id
          and   a.is_partner is null
          and   a.create_date between
                TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
                TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
    where create_date = max_create_date
    order by create_date

  • I need help with this code error "unreachable statement"

    the error_
    F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
    int index;
    ^
    F:\Java\Projects\Tools.java:71: missing return statement
    }//end delete method
    ^
    F:\Java\Projects\Tools.java:86: missing return statement
    }//end getrecod
    ^
    3 errors
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    public class Tools//tool class
    private int numberOfToolItems;
    private ToolItems[] toolArray = new ToolItems[10];
    public Tools()//array of tool
    numberOfToolItems = 0;
    for(int i = 0; i < toolArray.length; i++)//for loop to create the array tools
    toolArray[i] = new ToolItems();
    }//end for loop
    }//end of array of tools
    public int search(int id)//search mehtod
    int index = 0;
    while (index < numberOfToolItems)//while and if loop search
    if(toolArray[index].getID() == id)
    return index;
    else
    index ++;
    }//en while and if loop
    return -1;
    }//end search method
    public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
    if(numberOfToolItems >= toolArray.length)
    return 0;
    int index;
    index = search(id); <-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------HERE
    if (index == -1)
    toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
    numberInStock ++;
    return 1;
    }//end if index
    }//end if toolitem array
    return -1;
    }//end insert method
    public int delete(/*int id*/)//delete method
    }//end delete method
    public void display()//display method
    for(int i = 0; i < numberOfToolItems; i++)
    //toolArray.display(g,y,x);
    }//end display method
    public String getRecord(int i)//get record method
    // return toolArray[i].getName()+ "ID: "+toolArray[i].getID()
    }//end getrecod
    }//end class
    Edited by: ladsoftware on Oct 9, 2009 6:08 AM
    Edited by: ladsoftware on Oct 9, 2009 6:09 AM
    Edited by: ladsoftware on Oct 9, 2009 6:10 AM
    Edited by: ladsoftware on Oct 9, 2009 6:11 AM

    ladsoftware wrote:
    Subject: Re: I need help with this code error "unreachable statement"
    F:\Java\Projects\Tools.java:51: unreachable statement <-----------------------------------------------------------------------------------------------------------------THIS
    int index;
    ^
    F:\Java\Projects\Tools.java:71: missing return statement
    }//end delete method
    ^
    F:\Java\Projects\Tools.java:86: missing return statement
    }//end getrecod
    ^
    3 errorsThe compiler is telling you exactly what the problems are:
    public int insert(int id, int numberInStock, int quality, double basePrice, String nm)//insert method
    if(numberOfToolItems >= toolArray.length)
    return 0; // <<== HERE you return, so everyting in the if block after this is unreachable
    int index;
    index = search(id);  //< -----------------------------------------------------------------------------------------------------------------HERE
    if (index == -1)
    toolArray[index].assign(id,numberInStock, quality, basePrice,nm);
    numberInStock ++;
    return 1;
    }//end if index
    }//end if toolitem array
    return -1;
    }//end insert method
    public int delete(/*int id*/)//delete method
    // <<== HERE where is the return statement?
    }//end delete method
    public String getRecord(int i)//get record method
    // return toolArray.getName()+ "ID: "+toolArray[i].getID() <<== HERE you commented out the return statement
    }//end getrecod
    }//end class

  • Need help with this query

    Hi,
    I am using SQL Server 2008 Enterprise edition 64 bit on Windows serer 2008 enterprise edition 64 bit.
    The below query works fine. I am trying to rewrite the code without using the sub query. In the end i should get the same results for both the query which we are going to rewrite and the below mentioned query.
    Can any help me please.
    SELECT
    t1.DOCUMENT_NO,
    RTRIM(CAST(t1."ENVIRONMENT_CD" AS VARCHAR(5))) + '*' + RTRIM(CAST(t1."ORDER_NO" AS VARCHAR(25)))
    +
    CASE WHEN (SELECT COUNT(DISTINCT S1.TEST_REPORTING_MATERIAL_SID)
    FROM dbo.TBLTEST S1 ON S1.DOCUMENT_NO = T1.DOCUMENT_NO
    WHERE S1.TEST_REPORTING_MATERIAL_SID > 0
    AND S1.COMPANY_CD = T1.COMPANY_CD AND S1.INVOICE_SEQ_NO = T1.INVOICE_SEQ_NO
    AND S1.DOCUMENT_ITEM_NO = T1.DOCUMENT_ITEM_NO
    AND S1.ORDER_NO = T1.ORDER_NO) > 1 THEN
    RTRIM(CAST(t1."TEST_REPORTING_MATERIAL_SID" AS VARCHAR(10)))
    ELSE
    END as sum_key,
    t1.SALES_ANALYSIS_CD
    FROM
    dbo.TBLTEST_ALL T1
    WHERE
    t1.TIME_SID >= 20001001 ;
    I tried to use a left outer Join , it did not work out. I tried to take the subquery and assign it to a variable and use in the above mentioned query. But i am not getting the same results.
    I don't want to use the above query so i am planning to rewrite the code.
    Thank You,

    I doubt that the query you posted works fine, because:
    FROM dbo.TBLTEST S1 ON S1.DOCUMENT_NO = T1.DOCUMENT_NO
    This is a syntax error. I will have to assume that your inteded query reads:
    SELECT t1.DOCUMENT_NO,
           rtrim(cast(t1."ENVIRONMENT_CD" AS varchar(5))) + '*' +
           rtrim(cast(t1."ORDER_NO" AS varchar(25))) +
          CASE WHEN (SELECT COUNT(DISTINCT S1.TEST_REPORTING_MATERIAL_SID)
                     FROM   dbo.TBLTEST S1
                     WHERE  S1.DOCUMENT_NO = T1.DOCUMENT_NO
                       AND  S1.TEST_REPORTING_MATERIAL_SID > 0
                       AND  S1.COMPANY_CD = T1.COMPANY_CD
                       AND  S1.INVOICE_SEQ_NO = T1.INVOICE_SEQ_NO
                       AND  S1.DOCUMENT_ITEM_NO = T1.DOCUMENT_ITEM_NO
                       AND  S1.ORDER_NO = T1.ORDER_NO) > 1 THEN
                     RTRIM(CAST(t1."TEST_REPORTING_MATERIAL_SID" AS VARCHAR(10)))
               ELSE  '*-'
          END as sum_key, t1.SALES_ANALYSIS_CD
    FROM   dbo.TBLTEST_ALL T1
    WHERE  t1.TIME_SID >= 20001001
    Here is a query with a left join. Whether it is actually better than the one you have I am not sure.
    SELECT t1.DOCUMENT_NO,
           rtrim(cast(t1."ENVIRONMENT_CD" AS varchar(5))) + '*' +
           rtrim(cast(t1."ORDER_NO" AS varchar(25))) +
          CASE WHEN S1."EXISTS" IS NOT NULL
               THEN  RTRIM(CAST(t1."TEST_REPORTING_MATERIAL_SID" AS varchar(10)))
               ELSE  '*-'
          END as sum_key, t1.SALES_ANALYSIS_CD
    FROM   dbo.TBLTEST_ALL T1
    LEFT   JOIN (SELECT 1 AS "EXISTS"
                 FROM   dbo.TBLTEST
                 WHERE  TEST_REPORTING_MATERIAL_SID > 0
                 GROUP  BY DOCUMENT_NO, COMPANY_CD, INVOICE_SEQ_NO,
                           DOCUMENT_ITEM_NO, ORDER_NO
                 HAVING COUNT(DISTINCT TEST_REPORTING_MATERIAL_SID) > 1) AS S1
             ON S1.DOCUMENT_NO = T1.DOCUMENT_NO
           AND  S1.COMPANY_CD = T1.COMPANY_CD
           AND  S1.INVOICE_SEQ_NO = T1.INVOICE_SEQ_NO
           AND  S1.DOCUMENT_ITEM_NO = T1.DOCUMENT_ITEM_NO
           AND  S1.ORDER_NO = T1.ORDER_NO
    WHERE  t1.TIME_SID >= 20001001
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Need help on this query

    hi ,
    I have the following data and the expected results.
    Have managed to return the results in a procedure but the performance is not good.
    Could a analytic be used instead ? need advise
    logic
    1. if all type is of run then i'll simply get the id and its seq
    2. however , if the type is a if ...else then i'll need to check against table B and whether passing the if else will determine the seq to be used and if it passes the if then it'll go to the next id, if not if will go the else until it reaches the end of that section of if .. else for the same id before going to the next id
    table A
    id     seq     type          checkname     checkvalue     check          fail          nextseq     
    id0     1     run     
    id0     2     run
    id0     3     run
    id1     1     if          ac          5          =          3          
    id1     2     run                                                  end
    id1     3     elseif          ac          6          >=          4          
    id1     4     run
    id1     5     else                                                  end          
    id1     6     run          
    id2     1     run
    id2     2     run
    id2     3     if          an          5          <=          5
    id2     4     run
    id2     5     else                                                  end     
    id2     6     run
    scenario 1
    table B
    id     checkname     val
    id0     aa          0
    id1     ac          2
    id1     ab          8
    id2     ab          4
    id     an          5
    RESULTS :
    id     seq     
    id0     1
    id0     2
    id0     3
    id1     6
    id2     1
    id2     2
    id2     4
    scenario 2
    table B
    id     checkname     val
    id0     aa          0
    id1     ac          5
    id1     ab          8
    id2     ab          4
    id     an          6
    RESULTS :
    id     seq     
    id0     1
    id0     2
    id0     3
    id1     2
    id2     1
    id2     2
    id2     6appreciate ur advise
    tks & rgds

    ok,
    of course you can do it with model
    but still it can be done with analytic functions.
    one more question
    what is the condition to be checked?
    a.checkvalue || a.check || b.val
    or
    b.val || a.check || a.checkvalue
    accroding to your OP it seems the second choise is correct, isn't it?
    SQL> -- first scenario
    SQL>
    SQL> with tableA as (select 'id0' id, 1 seq, 'run' type, null checkname, null checkvalue, null check_, null fail, null nextseq from dual union all
      2                   select 'id0',    2,   'run',       null,null,null,null,null from dual union all
      3                   select 'id0',    3,   'run',       null,null,null,null,null from dual union all
      4                   select 'id1',    1,   'if',        'ac',5,'=',3,null from dual union all
      5                   select 'id1',    2,   'run',       null,null,null,null,'end' from dual union all
      6                   select 'id1',    3,   'elseif',    'ac',6,'>=',4,null from dual union all
      7                   select 'id1',    4,   'run',       null,null,null,null,null from dual union all
      8                   select 'id1',    5,   'else',      null,null,null,null,'end' from dual union all
      9                   select 'id1',    6,   'run',       null,null,null,null,null from dual union all
    10                   select 'id2',    1,   'run',       null,null,null,null,null from dual union all
    11                   select 'id2',    2,   'run',       null,null,null,null,null from dual union all
    12                   select 'id2',    3,   'if',        'an',5,'<=',5,null from dual union all
    13                   select 'id2',    4,   'run',       null,null,null,null,null from dual union all
    14                   select 'id2',    5,   'else',      null,null,null,null,'end' from dual union all
    15                   select 'id2',    6,   'run',       null,null,null,null,null from dual),
    16  tableB as (select 'id0' id, 'aa' checkname, 0 val from dual union all
    17             select 'id1', 'ac', 2 from dual union all
    18             select 'id1', 'ab', 8 from dual union all
    19             select 'id2', 'ab', 4 from dual union all
    20             select 'id2', 'an', 5 from dual)
    21             --
    22             select id, seq from (select tt.*, first_value(decode(flag,1,seq) ignore nulls) over (partition by id order by seq) FV from
    23             (select a.*, b.val, lag(nvl(nvl2(val,case check_ when '='  then decode(sign(val-checkvalue),0,1,0)
    24                                          when '>=' then decode(sign(val-checkvalue),-1,0,1)
    25                                          when '>'  then decode(sign(val-checkvalue),1,1,0)
    26                                          when '<=' then decode(sign(val-checkvalue),1,0,1)
    27                                          when '<'  then decode(sign(val-checkvalue),-1,1,0)
    28                                     end, decode(type,'else',1)),val)) over (partition by a.id order by seq)  flag, lag(type,1,type) over (partition by a.id order by seq) lag_type
    29                              from tableA a, tableB b
    30              where a.id=b.id(+)
    31                and a.checkname=b.checkname(+)
    32                order by 1,2) tt
    33  ) where (type='run' and lag_type='run') or seq=FV
    34  /
    ID         SEQ
    id0          1
    id0          2
    id0          3
    id1          6
    id2          1
    id2          2
    id2          4
    7 rows selected
    SQL> --second scenario
    SQL>
    SQL> with tableA as (select 'id0' id, 1 seq, 'run' type, null checkname, null checkvalue, null check_, null fail, null nextseq from dual union all
      2                   select 'id0',    2,   'run',       null,null,null,null,null from dual union all
      3                   select 'id0',    3,   'run',       null,null,null,null,null from dual union all
      4                   select 'id1',    1,   'if',        'ac',5,'=',3,null from dual union all
      5                   select 'id1',    2,   'run',       null,null,null,null,'end' from dual union all
      6                   select 'id1',    3,   'elseif',    'ac',6,'>=',4,null from dual union all
      7                   select 'id1',    4,   'run',       null,null,null,null,null from dual union all
      8                   select 'id1',    5,   'else',      null,null,null,null,'end' from dual union all
      9                   select 'id1',    6,   'run',       null,null,null,null,null from dual union all
    10                   select 'id2',    1,   'run',       null,null,null,null,null from dual union all
    11                   select 'id2',    2,   'run',       null,null,null,null,null from dual union all
    12                   select 'id2',    3,   'if',        'an',5,'<=',5,null from dual union all
    13                   select 'id2',    4,   'run',       null,null,null,null,null from dual union all
    14                   select 'id2',    5,   'else',      null,null,null,null,'end' from dual union all
    15                   select 'id2',    6,   'run',       null,null,null,null,null from dual),
    16  tableB as (select 'id0' id, 'aa' checkname, 0 val from dual union all
    17             select 'id1', 'ac', 5 from dual union all
    18             select 'id1', 'ab', 8 from dual union all
    19             select 'id2', 'ab', 4 from dual union all
    20             select 'id2', 'an', 6 from dual)
    21             --
    22             select id, seq from (select tt.*, first_value(decode(flag,1,seq) ignore nulls) over (partition by id order by seq) FV from
    23             (select a.*, b.val, lag(nvl(nvl2(val,case check_ when '='  then decode(sign(val-checkvalue),0,1,0)
    24                                          when '>=' then decode(sign(val-checkvalue),-1,0,1)
    25                                          when '>'  then decode(sign(val-checkvalue),1,1,0)
    26                                          when '<=' then decode(sign(val-checkvalue),1,0,1)
    27                                          when '<'  then decode(sign(val-checkvalue),-1,1,0)
    28                                     end, decode(type,'else',1)),val)) over (partition by a.id order by seq)  flag, lag(type,1,type) over (partition by a.id order by seq) lag_type
    29                              from tableA a, tableB b
    30              where a.id=b.id(+)
    31                and a.checkname=b.checkname(+)
    32                order by 1,2) tt
    33  ) where (type='run' and lag_type='run') or seq=FV
    34  /
    ID         SEQ
    id0          1
    id0          2
    id0          3
    id1          2
    id2          1
    id2          2
    id2          6
    7 rows selected
    SQL> Message was edited by:
    Volder
    1> In my query I don't use FAIL column
    so I go consequently throug SEQ column order.
    Using MODEL - you could use FAIL values as dimension values for getting the next row needed.
    2> In my query If there're no needed values in TABLE B - the else part of your IF_CLAUSES will be triggered.
    3> Instead of huge case you can just create function that will get inputted 3 params: 2 values and check operator - and will return 1 if true, 0 if it is false.
    Just take these comments into account.

  • SQL I need help with this query Please help

    List the names of all the products whose weight unit measure is “Gram”.  Order the list by product name.  Do not use JOINS, but use the IN clause with a sub-query.
    select Name
    from UnitMeasure
    where Name= 'Gram'
    order by Name
    I did this, but it seem that the requirement is different.

    As a guess:
    Select Name from Product
    where UnitMeasure in (Select Name from unitmeasure where name = 'Gram')
    Andy Tauber
    Data Architect
    The Vancouver Clinic
    Website | LinkedIn
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
    "Mark as Answer" and "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread.

  • Need help over this Query

    Hi, I need the Result set in the given below form. 
    Can any one please help me with this. 
    I am not able to get the 2nd most recent login date in the separate column. 
    Concerned Columns: Login date, login date2, login difference 
    Login date = Most recent login by the user
    Login date 2= 2nd most recent login by the user
    Login difference =  difference between last 2 logins 
    Help!!
    DECLARE @ownerid INT=304,@offset INT=330,@totalsec INT=86400
    SELECT USERNAME, LOGIN_ID,EMAIL,DEPARTMENT,LOGIN_DATE, LOGOUT_DATE, IP_ADDRESS,MACHINE_NAME,TOTAL_LOGIN_TIME,LOGIN_NUMBER,
    ROW_NUMBER() OVER (ORDER BY USERNAME, LOGIN_ID) AS ROWNUMBER
    FROM
    SELECT Usr.UserID [USERID], usr.UserName [USERNAME],usr.LoginID [LOGIN_ID],
    usrcontact.Email [EMAIL],
    UsrContact.Department [DEPARTMENT],
    MAX(DateAdd(mi,@offset, UsrHis.LoginDate)) [LOGIN_DATE],
    MAX(DateAdd(mi,@offset, UsrHis.LogoutDate)) [LOGOUT_DATE],
    UsrHis.IPAddress [IP_ADDRESS],UsrHis.MachineName [MACHINE_NAME],
    convert( NVARCHAR(50),(DATEDIFF(SECOND,UsrHis.LoginDate,UsrHis.LogoutDate))/@totalsec) + ' '+'Days'+ ' '+
    convert( NVARCHAR(50),((DATEDIFF(SECOND,UsrHis.LoginDate,UsrHis.LogoutDate))%@totalsec)/3600) + ' '+'hours'+ ' '+
    convert( NVARCHAR(50),(((DATEDIFF(SECOND,UsrHis.LoginDate,UsrHis.LogoutDate))%@totalsec)%3600/60)) + ' '+'Minutes'+ ' '+
    convert( NVARCHAR(50),(((DATEDIFF(SECOND,UsrHis.LoginDate,UsrHis.LogoutDate))%@totalsec)%3600%60)) + ' '+'Seconds'
    [TOTAL_LOGIN_TIME],
    ROW_NUMBER() OVER (PARTITION BY USR.USERID ORDER BY USRHIS.LOGINDATE) LOGIN_NUMBER
    FROM Az_User Usr Inner Join LoginHistory UsrHis
    ON UsrHis.OwnerID=Usr.AppOwnerID
    and
    Usr.UserID = UsrHis.UserID
    inner join UserContact UsrContact
    ON UsrContact.CompanyID = Usr.AppOwnerID
    and UsrContact.UserID = Usr.UserID
    WHERE usr.AppOwnerID = @ownerid
    GROUP BY Usr.UserID,Usr.UserName , usrcontact.Email , UsrHis.LoginDate,usr.LoginID,UsrContact.Department,
    UsrHis.LogoutDate,UsrHis.IPAddress,UsrHis.MachineName,
    Dateadd(D, Datediff(D, 0, Dateadd(mi, @offset, UsrHis.LoginDate)), 0)
    ) AS TEMP
    WHERE TEMP.LOGIN_NUMBER <=2
    Hi here is the Data type of the columns i am selecting.. and the result i am getting. 
    But here the total_login_time is wrong. .
    I need difference between last 2 logins not length of the session.  

    It is unclear what you are trying to achieve... 
    DATEDIFF(d,Logindate,Logindate2)
    AS [Login difference]
    FROM.....
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Hi.. I need help and this is my Case ID: 460793800 .. I can't add my phone corectly in your website.. This is my mobile no.  966596005260 please call me

    I can not use my itones to download or up date beacous my App account is desapled

    Several points:
    I do not have a relevant website.
    You are not addressing Apple. This is a user-to-user support site.
    Your case number is therefore meaningless here.
    Nobody here is going to call your mobile. We do not even know what country you are in.
    It is a dumb idea to display your mobile number on a public forum.

  • Physician/Researcher needs help with this query

    Folks,
    Thank you in advance for looking at my problem. You are helping to save lives and make this world a better place.
    I am trying to find out the earliest date patients took steroid. I have:
    select patientid, visitnumber, steroid_start_date from treatments where steroid_start_date is not null and trim(steroid_start_date) != '/'
    order by patientid, substr(steroid_start_date, -4)
    I then have:
    patientid visitnumber steroid_start_date(this is a string column, not date or time, and it has so many junk in it, like /2003 , /)
    4 3 03/2004
    4 2 01/01/2005
    10 2 08/01/2005
    10 1 05/01/2002
    What I need is:
    4 3 03/2004
    10 1 05/01/2002
    I am not good with group by... having.... max.... How can I limit to one patient per row and this row is their earliest visit?
    Thank you very much in advance. You are helping to save lives.

    Here it is ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:00.53
    satyaki>
    satyaki>
    satyaki>with t
      2  as
      3    (
      4       select 4 patientid, 3 visitnumber, '03/2004' steroid_start_date from dual
      5       union all
      6       select 4, 2, '01/01/2005' from dual
      7       union all
      8       select 10, 2, '08/01/2005' from dual
      9       union all
    10       select 10, 1, '05/01/2002' from dual
    11    )
    12  select patientid,
    13         visitnumber,
    14         steroid_start_date
    15  from (
    16         select k.*,
    17                row_number() over(partition by patientid order by to_date(substr(steroid_start_date,-4),'YYYY')) rn
    18         from t k
    19         order by patientid
    20       )
    21  where rn=1;
    PATIENTID VISITNUMBER STEROID_ST
             4           3 03/2004
            10           1 05/01/2002
    Elapsed: 00:00:00.11
    satyaki>Regards.
    Satyaki De.

  • Need help in this query

    Dear all,
    I am quite a beginner and assigned a critical task, here is the table contents and below is the function.
    function returns the access permission(M or V) of user, the task here is if user is already
    defined in the table it gets the access flag value. But my problem here is if it is not defined
    in the table it should get department accessflag without any explicit initialization in the function.
    SQL> SELECT * FROM PACS;
    BRANCH     DEPT       ACCESSFLAG USERID
    HO         FIN        M        NANDA
    HO         FIN        M        RAVI
    HO         FIN        V
    HO         MKT        M        GOPAL
    HO         MKT        M        KISHORE
    HO         MKT        V
    HO         FOC        M           SAILESH
    HO         FOC        V
    Create Or Replace
    Function GetAccessFlag(IBranch In VarChar2,
                     IDept In VarChar2,
                     IUserId In VarChar2)
    Return Varchar2
    Is
         LvAccess VarChar2(2);
    Begin
         Begin
              Select AccessFlag
              Into LvAccess
              From Pacs
              Where (Branch = IBranch Or (IBranch Is Null))
              And   (Dept   = IDept Or (IDept is Null))
              And   (UserId = IUserId Or (IUserId Is Null));
         Exception
              When No_Data_Found Then
                   Raise_Application_Error(-20001, 'No Acess permissions defined');               
              When Others Then
                   Raise_Application_Error(-20002, 'Other Error - '||SqlErrM);
         End;
         Return     (LvAccess);
    End GetAccessFlag;thank you very much in advance.

    I prepared small example for you:
    <pre>
    [email protected]> create table pacs(
    2 branch char(2) not null,
    3 dept char(3) not null,
    4 accessflag char(1) not null,
    5 userid varchar2(10)
    6 )
    7 /
    Table created.
    [email protected]> insert into pacs values('HO','FIN','M','NANDA');
    1 row created.
    [email protected]> insert into pacs values('HO','FIN','M','RAVI');
    1 row created.
    [email protected]> insert into pacs values('HO','FIN','V',null);
    1 row created.
    [email protected]> insert into pacs values('HO','MKT','M','GOPAL');
    1 row created.
    [email protected]> insert into pacs values('HO','MKT','M','KISHORE');
    1 row created.
    [email protected]> insert into pacs values('HO','MKT','V',NULL);
    1 row created.
    [email protected]> insert into pacs values('HO','FOC','M','SAILESH');
    1 row created.
    [email protected]> insert into pacs values('HO','FOC','V',NULL);
    1 row created.
    [email protected]> commit;
    Commit complete.
    [email protected]> create or replace function getAccessFlag(p_Branch char,p_Dept char,
    2 p_Username varchar2)
    3 return char
    4 is
    5 no_data_for_user exception;
    6 v_result char;
    7
    8 function checkAccess(p_B char, p_D char, p_U varchar2)
    9 return char is
    10 v_access char;
    11 function checkUserAccess(p_B char, p_D char, p_U varchar2)
    12 return char is
    13 v_access char;
    14 begin
    15 select accessflag
    16 into v_access
    17 from pacs
    18 where branch = p_B and dept = p_D and userid = p_U;
    19 return v_access;
    20 exception
    21 when no_data_found then
    22 raise no_data_for_user;
    23 end;
    24 begin
    25 v_access := checkUserAccess(p_B, p_D, p_U);
    26 return v_access;
    27 exception
    28 when no_data_for_user then
    29 select accessflag
    30 into v_access
    31 from pacs
    32 where branch = p_B and dept = p_D and userid is null;
    33 return v_access;
    34 end;
    35 begin
    36 v_result := checkAccess(p_Branch, p_Dept, p_Username);
    37 return v_result;
    38 exception
    39 when no_data_found then
    40 raise_application_error(-20001,'No data for user and department');
    41 end;
    42 /
    Function created.
    [email protected]> select getAccessFlag('HO','FU','Krystian') from dual;
    select getAccessFlag('HO','FU','Krystian') from dual
    ERROR at line 1:
    ORA-20001: No data for user and department
    ORA-06512: at "MOB.GETACCESSFLAG", line 40
    [email protected]> select getAccessFlag('HO','FIN','Krystian') from dual;
    GETACCESSFLAG('HO','FIN','KRYSTIAN')
    V
    [email protected]> select getAccessFlag('HO','FIN','NANDA') from dual;
    GETACCESSFLAG('HO','FIN','NANDA')
    M
    [email protected]>
    </pre>
    Best Regards
    Krystian Zieja / mob

  • Please, need help with a query

    Hi !
    Please need help with this query:
    Needs to show (in cases of more than 1 loan offer) the latest create_date one time.
    Meaning, In cases the USER_ID, LOAN_ID, CREATE_DATE are the same need to show only the latest, Thanks!!!
    select distinct a.id,
    create_date,
    a.loanid,
    a.rate,
    a.pays,
    a.gracetime,
    a.emailtosend,
    d.first_name,
    d.last_name,
    a.user_id
    from CLAL_LOANCALC_DET a,
    loan_Calculator b,
    bv_user_profile c,
    bv_mr_user_profile d
    where b.loanid = a.loanid
    and c.NET_USER_NO = a.resp_id
    and d.user_id = c.user_id
    and a.is_partner is null
    and a.create_date between
    TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
    TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
    order by a.create_date

    Take a look on the syntax :
    max(...) keep (dense_rank last order by ...)
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions056.htm#i1000901
    Nicolas.

  • Need help defining a query

    Hi everyone...
    I need help with this query. The table 'cobros' has a primary key defined by id_cliente + id_cobro. I pretend to classify rows by COUNT(id_cobro) which are between a date range.
    A client could have 1 or 2 or 3 rows per day, no more for a specific date. I would like to get first, all clients with COUNT(id_cobro) = 1, all clients with COUNT(id_cobro) = 2, and finally all clients with COUNT(id_cobro) = 3.
    Something similar to:
    1 SELECT id_cliente, COUNT(id_cobro) FROM cobros
    2 WHERE fecha_proximo_cobro >= '2011-05-30 00:00'
    3 AND fecha_proximo_cobro <= '2011-05-30 23:59'
    4 AND COUNT(id_cobro) = 1
    5 GROUP BY id_cliente
    The fourth line is the problem. It doesn't work.
    Thanks in advance!!!
    Mario

    Maybe you are looking for something like this?
    SELECT id_cliente
         , COUNT(*)   AS cnt
    FROM   cobros
    WHERE  fecha_promixo_cobro BETWEEN TO_DATE('2011-05-30 00:00','YYYY-MM-DD HH24:MI') AND TO_DATE('2011-05-30 23:59','YYYY-MM-DD HH24:MI')
    GROUP BY id_cliente
    ORDER BY 2
           , 1Also, NEVER rely on implicit data type conversion as you have (you provide a STRING not a DATE).
    Edited by: Centinul on Jun 2, 2011 12:36 PM
    Fixed syntax error.

  • Need help in this sql query to use Case Statement

    hi All,
    I have the below query -
    SELECT DISTINCT OFFC.PROV_ID
    ,OFFC.WK_DAY
    ,CASE
    WHEN OFFC.WK_DAY ='MONDAY' THEN 1
    WHEN OFFC.WK_DAY ='TUESDAY' THEN 2
    WHEN OFFC.WK_DAY ='WEDNESDAY' THEN 3
    WHEN OFFC.WK_DAY ='THURSDAY' THEN 4
    WHEN OFFC.WK_DAY ='FRIDAY' THEN 5
    WHEN OFFC.WK_DAY ='SATURDAY' THEN 6
    WHEN OFFC.WK_DAY ='SUNDAY' THEN 7
    END AS DOW
    ,OFFC.OFFC_OPENG_TIME
    ,OFFC.OFFC_CLSNG_TIME
    FROM GGDD.PROV_OFFC_HR OFFC
    WHERE OFFC.PROV_ID='0000600'
    WITH UR;
    this query is bringing results in 6 differnt rows with opening and closing time for each day separately. I want to generate the data in one row with each day having opening and closing time, so for 7 days, total 14 columns with opening and closing time. But i am not able to do that using case statement.
    can somebody help me in achieving that.
    thanks,
    iamhere

    Hi,
    Welcome to the forum!
    That's called a Pivot .
    Instead of having 1CASE expression, have 14, one for the opening and one for the closing time each day, and do GROUP BY to combine them onto one row.
    SELECT       OFFC.PROV_ID
    ,       MIN (CASE WHEN OFFC.WK_DAY ='MONDAY'    THEN OFFC.OFFC_OPENG_TIME END)     AS mon_opn
    ,       MIN (CASE WHEN OFFC.WK_DAY ='MONDAY'    THEN OFFC.OFFC_CLSNG_TIME END)     AS mon_cls
    ,       MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY'   THEN OFFC.OFFC_OPENG_TIME END)     AS tue_opn
    ,       MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY'   THEN OFFC.OFFC_CLSNG_TIME END)     AS tue_cls
    FROM        GGDD.PROV_OFFC_HR OFFC
    WHERE       OFFC.PROV_ID     = '0000600'
    GROUP BY  offc.prov_id
    ;This assumes there is (at most) only one row in the table for each distinct prov_id and weekday. If not, what do you want to do? Post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
    The staement above works in Oracle 8.1 and up, but there's a better way (SELECT ... PIVOT) available in Oracle 11. What version are you using? (It's always a good idea to include this when you post a question.)
    Edited by: Frank Kulash on Jan 6, 2011 8:22 PM

  • Please help to re-write this query using exists or with

    Hi please help to re-write this query using exists or with, i need to write same code for 45 day , 90 days and so on but sub query condition is same for all
    SELECT SUM (DECODE (t_one_mon_c_paid_us, 0, 0, 1)) t_two_y_m_mul_ca_
    FROM (SELECT SUM (one_mon_c_paid_us) t_one_mon_c_paid_us
    FROM (
    SELECT a.individual_id individual_id,
    CASE
    WHEN NVL
    (b.ship_dt,
    TO_DATE ('05-MAY-1955')
    ) >= SYSDATE - 45
    AND a.country_cd = 'US'
    AND b.individual_id in (
    SELECT UNIQUE c.individual_id
    FROM order c
    WHERE c.prod_cd = 'A'
    AND NVL (c.last_payment_dt,
    TO_DATE ('05-MAY-1955')
    ) >= SYSDATE - 745)
    THEN 1
    ELSE 0
    END AS one_mon_c_paid_us
    FROM items b, addr a, product d
    WHERE b.prod_id = d.prod_id
    AND d.affinity_1_cd = 'ADH'
    AND b.individual_id = a.individual_id)
    GROUP BY individual_id)
    Edited by: user4522368 on Aug 23, 2010 9:11 AM

    Please try and place \ before and after you code \Could you not remove the inline column select with the following?
    SELECT a.individual_id individual_id
         ,CASE
            when b.Ship_dt is null then
              3
            WHEN b.ship_dt >= SYSDATE - 90
              3
            WHEN b.ship_dt >= SYSDATE - 45
              2
            WHEN b.ship_dt >= SYSDATE - 30
              1
          END AS one_mon_c_paid_us
    FROM  items           b
         ,addr            a
         ,product         d
         ,order           o
    WHERE b.prod_id       = d.prod_id
    AND   d.affinity_1_cd = 'ADH'
    AND   b.individual_id = a.individual_id
    AND   b.Individual_ID = o.Individual_ID
    and   o.Prod_CD       = 'A'             
    and   NVL (o.last_payment_dt,TO_DATE ('05-MAY-1955') ) >= SYSDATE - 745
    and   a.Country_CD    = 'US'

  • I need help I tried to use cloud backup on my iPhone 5.0.1 and after all my camera roll pictures are blurry and videos canot be played messege says URL not on this server ! Please help!! iPhone 4S, iOS 5.0.1

    I need help I tried to use cloud backup on my iPhone 5.0.1 and after all my camera roll pictures are blurry and videos canot be played messege says URL not on this server ! Please help!!
    iPhone 4S, iOS 5.0.1

    Try updating to iOS 6.1.3.

Maybe you are looking for

  • Viewing Layouts on Remote/Testing Server

    This is a beginner question. I'm trying to view Layouts and/or Content Holders on the Remote/Testing Server out of Dreamweaver so I can edit them independently, but I just get 404 messages. When I create a new page in BC, I am prompted for a Page Tit

  • How do I create a slide where users can upload a file to server or email a file?

    Could anyone guide me in how I could go about creating a slide where users can either email a file or upload it to my server? Any help would be greatly appriciated... Steve

  • Versions of Muse different between Mac and Windows

    Me and a friend wanted to test Adobe Muse and we installed the 30 days trial version. I did it on my Mac. My friend on his Windows PC. I've tried Muse and when I wanted to show what I did to my friend, I went to him with the .muse file on a USB stick

  • Powerbook RAM in MacBook Pro

    I'm sure this is probably not possible, but worth a shot. Can I transfer the 1GB RAM chip in my Powerbook G4 15" 1.5Ghz to my new MacBook Pro 2.0Ghz?

  • 5.1 with stereo but not surround?!

    I am experiencing an odd problem with my surround sound. I have a 5.1 surround system with the Sound Blaster Zx card and I noticed last night the surround sound did not sound right. I ran it through the sound test in the Pro Studio control panel and