Pls help with this query

Hello
If I run the following query I correctly get a sum of the invoices for a particular BP for Jan 09
SELECT T1.[SlpName], T0.[CardCode], SUM(CASE WHEN  T2.[DocDate] BETWEEN '20090101' AND '20090131' THEN (T2.[DocTotal] -  T2.[VatSum]) ELSE 0 END) AS 'JAN 09' FROM OCRD T0  INNER JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode INNER JOIN OINV T2 ON T0.CardCode = T2.CardCode WHERE T0.[CardCode] = 'KEY065' GROUP BY T0.[CardCode], T1.[SlpName]
However I need the value of credit notes to be reflected in the figure so I amended the query to be:
SELECT T1.[SlpName], T0.[CardCode], SUM(CASE WHEN  T2.[DocDate] BETWEEN '20090101' AND '20090131' THEN (T2.[DocTotal] -  T2.[VatSum])ELSE 0 END) - SUM(CASE WHEN  T3.[DocDate] BETWEEN '20090101' AND '20090131' THEN (T3.[DocTotal] -  T3.[VatSum]) ELSE 0 END) AS 'JAN 09' FROM OCRD T0  INNER JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode INNER JOIN OINV T2 ON T0.CardCode = T2.CardCode INNER JOIN ORIN T3 ON T0.CardCode = T3.CardCode WHERE T0.[CardCode] = 'KEY065' GROUP BY T0.[CardCode], T1.[SlpName]
When I run this query the output is incorrect ................ Is the fault to do with my JOINS?
Thanks

Hi Just to clarify
This query, which just totals any invoices for a BP for January, correctly returns a value of £9660.44 :
SELECT T1.[SlpName], T0.[CardCode], SUM(CASE WHEN  T2.[DocDate] BETWEEN '20090101' AND '20090131' THEN (T2.[DocTotal] -  T2.[VatSum]) ELSE 0 END) AS 'JAN 09' FROM OCRD T0  INNER JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode INNER JOIN OINV T2 ON T0.CardCode = T2.CardCode  WHERE T0.[CardCode] = 'KEY065' GROUP BY T0.[CardCode], T1.[SlpName]
This next query, which just totals any credit notes for a BP in January, correctly returns a value of £567.73 :
SELECT T1.[SlpName], T0.[CardCode], SUM(CASE WHEN  T3.[DocDate] BETWEEN '20090101' AND '20090131' THEN (T3.[DocTotal] -  T3.[VatSum]) ELSE 0 END) AS 'JAN 09' FROM OCRD T0  INNER JOIN OSLP T1 ON T0.SlpCode = T1.SlpCode INNER JOIN ORIN T3 ON T0.CardCode = T3.CardCode WHERE T0.[CardCode] = 'KEY065' GROUP BY T0.[CardCode], T1.[SlpName]
I want a query which return a value of 9660.44 minus 567.73 (ie £9092.71)
My original effort at this returned -£82,608.65 !!!!!!!!!
and Gordon's amended version returned -£40,281.74 !!!!!
Thanks for your patience
Steve

Similar Messages

  • Pls Help with this

    Hi,
    I need a help to resolve my problem.Actually i have a JSP page with a list box. When i select some value in the list box, appropriate values must list out according to the selected value.And i have a submit button to process that jsp page.
    I wrote a validation as all the fields must be entered to submit a page.
    But when i tried with the following code,it's just moving to processing page when i select a values from the list box.This is happening when i cheked the validation.
    Pls help with this code.This is very urgent.
    Code is as follows
    "Example1.jsp"
    <%
    String str1 = request.getParameter("Modem");
    %>
    <html>
    <head>
    <script language = "JavaScript">
    function Validate()
    if(document.UpdateFiosAccounts.Modem.value == "Select One")
    alert("Please select the value")
    document.UpdateFiosAccounts.Modem.focus()
    return false
    if(document.UpdateFiosAccounts.text1.value == "")
    alert("Please type some text")
    document.UpdateFiosAccounts.text1.focus()
    return false
    return true
    </script>
    </head>
    <body>
    <form name = "UpdateFiosAccounts" action="./Example1.jsp" method ="post" onSubmit= "return Validate()">
    Pls select One:<select name="Modem" size="1" onChange="document.UpdateFiosAccounts.submit()">
    <%
    if(str1 == null)
    %>
         <option value="Select One">Select One</option>
         <option value="One">One</option>
         <option value="Two">Two</option>
         <option value="Three">Three</option>
         <option value="Four">Four</option>
    <%
    else
    %>
         <option value="<%=str1%>"><%=str1%></option>
    <%
    %>
    </select><br>
    Pls type something: <input type ="text" name="text1">
    <input type ="submit" value="submit" onClick="document.UpdateFiosAccounts.action='./Accounts.jsp'">
    </form>
    </body>
    </html>

    Hi! The reason is that in the onChange property you are doing the submit, so, when you select something, it goes automatically and never pases through your validation function. So, remove that onChange. Next, the button is a submit buton, so, no matter what your validation does, the page will go. You need to change the submit type of the button to just button (<input type="button" onclick="function to validate">) and then you will get what you want. By the way, this is NOT a Java question, is more JavaScript question.
    Hope this helps.

  • 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

  • Can any one help with this query please

    I have a table something as below
    Things_t
    Things Characteristic Char Value
    Item 1 Colour Red
    Item 1 Packaging
    Item 2 Shape Square
    Item 2 Brand Spunk
    Now i want to reterive an item with none of its char values as Null. Using the query “ select distinct things from things_t where char value is Null ” will fetch the item 1 also together with item 2. i want to fetch a record from thing for which none of the char values are Null such as Item 2. Can you please help me with this query.

    Try this:
    WITH t AS
    (SELECT 1 item_id, 17436 chr_id, 14225034 chr_val_id FROM dual UNION
    SELECT 1 item_id, 39 chr_id, 14276173 chr_val_id FROM dual UNION
    SELECT 1 item_id, 17774 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 1 item_id, 265 chr_id, 20502978 chr_val_id FROM dual UNION
    SELECT 1 item_id, 16978 chr_id, 797233 chr_val_id FROM dual UNION
    SELECT 1 item_id, 13092 chr_id, 5666917 chr_val_id FROM dual UNION
    SELECT 1 item_id, 15228 chr_id, 1209758 chr_val_id FROM dual UNION
    SELECT 2 item_id, 112 chr_id,  12705342 chr_val_id FROM dual UNION
    SELECT 2 item_id, 6945 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 2 item_id, 70 chr_id, 12597376 chr_val_id FROM dual UNION
    SELECT 2 item_id, 16832 chr_id, NULL chr_val_id FROM dual UNION
    SELECT 2 item_id, 7886 chr_id, 9588619 chr_val_id FROM dual UNION
    SELECT 2 item_id, 6986 chr_id, 2659351 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9531 chr_id, 8910943 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9798 chr_id, 8717531 chr_val_id FROM dual UNION
    SELECT 3 item_id, 17446 chr_id, 12266441 chr_val_id FROM dual UNION
    SELECT 3 item_id, 4830 chr_id, 13683090 chr_val_id FROM dual UNION
    SELECT 3 item_id, 9518 chr_id, 834772 chr_val_id FROM dual UNION
    SELECT 3 item_id, 11031 chr_id, 20233753 chr_val_id FROM dual UNION
    SELECT 3 item_id, 12564 chr_id, 2282478 chr_val_id FROM dual)
    SELECT DISTINCT item_id
    FROM   t
    MINUS
    SELECT DISTINCT item_id
    FROM   t
    WHERE  chr_val_id IS NULLOr this:
    SELECT item_id
    FROM  (SELECT   item_id,
                    MIN(NVL(chr_val_id, -1)) min_chr_val_id
           FROM     t
           GROUP BY item_id)
    WHERE  min_chr_val_id != -1Edited by: lee200 on Oct 15, 2012 9:22 AM

  • Pls help in this query

    Hi,
    I've needed to print output like below. pls help me out .
    Thanks & Regards,
    Ramana.

    SQL> select '*****'||chr(10)||'****'||chr(10)||'***'||chr(10)||'**'||chr(10)||'*' from dual;
    '*****'||CHR(10)||'
    SQL>

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

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

  • Can anyone help with this query

    create table customer(
    customer_email varchar(100) not null
    ,cust_id int not null
    ,constraint pk__customer primary key clustered(cust_id)
    Please help ASAP
    create table purchase (
    purchase_id int not null identity(1,1)
    ,cust_id int not null references customer(cust_id)
    ,product_name varchar(200) not null
    ,amount int not null
    ,constraint pk__purchase primary key clustered (purchase_id)
    Write a query that returns one row per customer with the following columns. Don't forget about customers with no purchases.
    customer_email
    qty of purchase
    sum of purchase amount

    Homework deadline looming?
    This will work in versions of Oracle from 9 up, and in all versions of Sybase/ SQL Server (which you seem to wnat based on the CREATE TABLE syntax).
    SELECT customer_email, COUNT(*) number_purchaes, SUM(amount) total_purchases
    FROM customer c
         LEFT OUTER JOIN purchases p ON c.cust_id = p.cust_id
    GROUP BY customer_emailTTFN
    John

  • Pls Help with a query

    Problem Scope:
    Two tables with different set of columns,
    Only common column being "emplid"--employee id.
    table1 has 2 columns "emplid" and "effdt"- effective date.
    table2 has 3 columns "emplid", "start date" and "end date".
    So structure of the tables will be:
    1. table1: emplid, effdt
    2. table2: emplid, start_date, end_date
    Need to find out all the records from table2, where
    "table2.start_date" falls between 2 "table1.effdt" rows for the same employee.
    For example for an emplid "G1234",
    table 1 data: emplid, effdt
    G1234, 01/01/1990
    G1234, 01/01/1994
    table 2 data: emplid, start date
    G1234, 01/01/1993
    G1234, 01/01/2001
    For the above scenario, query should return the row: G1234, 01/01/1993 from table 2 as it(start date) falls between two effdt from table 1.
    Pls advice,
    Thanks

    Seems to be my day for LAG and LEAD.
    Does this work for you?
    SQL> SELECT * FROM t1;
         EMPID EFF_DT
          1234 01-jan-1990
          1234 01-jan-1994
    SQL> SELECT * FROM t2;
         EMPID START_DT    END_DT
          1234 01-jan-1993 31-dec-2000
          1234 01-jan-2001
    SQL> SELECT t2.empid, t2.start_dt, t2.end_dt
      2  FROM t2,
      3       (SELECT empid, eff_dt,
      4               LEAD(eff_dt) OVER (PARTITION BY empid
      5                                  ORDER BY eff_dt) next_eff
      6        FROM t1) t1
      7  WHERE t2.empid = t1.empid and
      8        t2.start_dt BETWEEN t1.eff_dt and t1.next_eff;
         EMPID START_DT    END_DT
          1234 01-jan-1993 31-dec-2000John

  • Pls. help tune this query

    This is the SQL i would like to tune for performace...
    The table structure is given below.
    The table has about 5 million rows.
    On the first day, load_flag has all the rows as 'I'.
    Then from the second day onwards only around 10% of records will be between Load_Start_Time and Load_End_Time. Among these around 40% will have Record_key like 'TP%'. And among those most of the records (95%)will have load_flag as 'U' and a very few (5%) as 'I'. At present there are unique and primary key indexes on record_key. Please advice me whether it's better to go for an index on any of these columns and what type would be better. I thought it would help to have a bit map index on load_flag and a function base index on SUBSTR (RECORD_KEY).
    Also pls. let me know if the order of predicates is right.
    Thanks in advance.
    M_STG_TPDB_TPD_TL_W_PH_LOI_CNTBLTY_STATUS_CE     SQ_STG_TPD_STG_TL_CS_EXTRACTED_RECS_MOD     "SELECT TPD_STG_TL_CS_EXTRACTED_RECS.RECORD_KEY, TPD_STG_TL_CS_EXTRACTED_RECS.DATA_SOURCE, TPD_STG_TL_CS_EXTRACTED_RECS.CONTACTABLE_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.LEGAL_OWNERSHIP_ISSUE_IND, TPD_STG_TL_CS_EXTRACTED_RECS.ADMIN_CONTROL_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.BANKRUPTCY_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.ASSIGNED_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.IN_TRUST_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.DIVORCE_CASE_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.POA_COP_INDICATOR, TPD_STG_TL_CS_EXTRACTED_RECS.SOURCE_EXTRACT_DATE_TIME
    FROM
    TPD_STG_TL_CS_EXTRACTED_RECS
    WHERE
    LOAD_FLAG IN ('I','U')
    AND SUBSTR (RECORD_KEY, 1,2)='TP'
    AND STG_UPDATE_DATE_TIME>'$$Load_Start_Time'
    AND STG_UPDATE_DATE_TIME<='$$Load_End_Time'"
    Table structure
    CREATE TABLE TPD_STG_TL_CS_EXTRACTED_RECS
    RECORD_KEY VARCHAR2(35 BYTE),
    SCHEME_NAME VARCHAR2(50 BYTE),
    ORGANISATION_NAME VARCHAR2(50 BYTE),
    SUPERIOR_TITLE_1 VARCHAR2(50 BYTE),
    TITLE_1 VARCHAR2(50 BYTE),
    FIRST_NAME_1 VARCHAR2(50 BYTE),
    MIDDLE_NAME_1 VARCHAR2(50 BYTE),
    SURNAME_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_1_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_2_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_3_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_4_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_5_1 VARCHAR2(50 BYTE),
    ADDRESS_LINE_6_1 VARCHAR2(50 BYTE),
    POST_CODE_1 VARCHAR2(12 BYTE),
    COUNTRY_1 VARCHAR2(50 BYTE),
    OVERSEAS_INDICATOR_1 CHAR(1 BYTE),
    DOB_1 NUMBER(8),
    GENDER_1 CHAR(1 BYTE),
    NINO_1 VARCHAR2(9 BYTE),
    DEATH_INDICATOR_1 CHAR(1 BYTE),
    PRODUCT_HOLDING_ROLE_TYPE_1 VARCHAR2(21 BYTE),
    GONE_AWAY_INDICATOR_1 CHAR(1 BYTE),
    THAMES_LEGAL_OWNERSHIP_IND_1 CHAR(1 BYTE),
    SOURCE_SYSTEM_PARTY_INDV_ID_1 VARCHAR2(15 BYTE),
    SUPERIOR_TITLE_2 VARCHAR2(50 BYTE),
    TITLE_2 VARCHAR2(50 BYTE),
    FIRST_NAME_2 VARCHAR2(50 BYTE),
    MIDDLE_NAME_2 VARCHAR2(50 BYTE),
    SURNAME_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_1_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_2_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_3_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_4_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_5_2 VARCHAR2(50 BYTE),
    ADDRESS_LINE_6_2 VARCHAR2(50 BYTE),
    POST_CODE_2 VARCHAR2(12 BYTE),
    COUNTRY_2 VARCHAR2(50 BYTE),
    OVERSEAS_INDICATOR_2 CHAR(1 BYTE),
    DOB_2 NUMBER(8),
    GENDER_2 CHAR(1 BYTE),
    NINO_2 VARCHAR2(9 BYTE),
    DEATH_INDICATOR_2 CHAR(1 BYTE),
    PRODUCT_HOLDING_ROLE_TYPE_2 VARCHAR2(21 BYTE),
    GONE_AWAY_INDICATOR_2 CHAR(1 BYTE),
    THAMES_LEGAL_OWNERSHIP_IND_2 CHAR(1 BYTE),
    SOURCE_SYSTEM_PARTY_INDV_ID_2 VARCHAR2(15 BYTE),
    JOINT_OWNER_INDICATOR CHAR(1 BYTE),
    JOINT_LIFE_TYPE NUMBER(1),
    SAME_ADDRESS_INDICATOR CHAR(1 BYTE),
    TITLE_LA1 VARCHAR2(50 BYTE),
    FIRST_NAME_LA1 VARCHAR2(50 BYTE),
    SURNAME_LA1 VARCHAR2(50 BYTE),
    DOB_LA1 NUMBER(8),
    TITLE_LA2 VARCHAR2(50 BYTE),
    FIRST_NAME_LA2 VARCHAR2(50 BYTE),
    SURNAME_LA2 VARCHAR2(50 BYTE),
    DOB_LA2 NUMBER(8),
    PRODUCT_HOLDING_REF_NUMBER VARCHAR2(28 BYTE),
    PARENT_PRODUCT_HOLDING_REF_NUM VARCHAR2(9 BYTE),
    OCDB_REFERENCE_NUMBER VARCHAR2(17 BYTE),
    BUSINESS_GROUP CHAR(3 BYTE),
    SCHEME_NUMBER VARCHAR2(8 BYTE),
    TRUSTEE_SEQUENCE_NUMBER NUMBER(10),
    MEMBER_NUMBER VARCHAR2(10 BYTE),
    PRSN_ID NUMBER(10),
    OLD_SCHEME_NUMBER VARCHAR2(8 BYTE),
    PUBLIC_SECTOR_INDICATOR CHAR(1 BYTE),
    ELIGIBLE_INDICATOR CHAR(1 BYTE),
    SCHEME_STATUS NUMBER(1),
    SCHEME_TYPE CHAR(2 BYTE),
    Q_DATE_WITH_PROFIT_STATUS NUMBER(1),
    A_DATE_WITH_PROFIT_STATUS NUMBER(1),
    LATEST_WITH_PROFIT_STATUS NUMBER(1),
    NPSW_INDICATOR CHAR(1 BYTE),
    PRODUCT_HOLDING_STATUS CHAR(1 BYTE),
    MATURITY_DATE_OF_CONTRACT NUMBER(8),
    DUE_END_DATE_OF_CONTRACT NUMBER(8),
    OUT_OF_FORCE_DATE NUMBER(8),
    OUT_OF_FORCE_REASON_CODE NUMBER(2),
    DATA_SOURCE VARCHAR2(3 BYTE),
    PRODUCT_TYPE VARCHAR2(30 BYTE),
    PRODUCT_DESCRIPTION VARCHAR2(50 BYTE),
    SERVICING_AGENT_NUMBER VARCHAR2(10 BYTE),
    CONTACTABLE_INDICATOR CHAR(1 BYTE),
    LEGAL_OWNERSHIP_ISSUE_IND CHAR(1 BYTE),
    ADMIN_CONTROL_INDICATOR CHAR(1 BYTE),
    BANKRUPTCY_INDICATOR CHAR(1 BYTE),
    ASSIGNED_INDICATOR CHAR(1 BYTE),
    IN_TRUST_INDICATOR CHAR(1 BYTE),
    DIVORCE_CASE_INDICATOR CHAR(1 BYTE),
    POA_COP_INDICATOR CHAR(1 BYTE),
    DONOR_POLICY_INDICATOR CHAR(1 BYTE),
    TAX_JURISDICTION NUMBER(2),
    INELIGIBLE_DATE NUMBER(8),
    INELIGIBILITY_REASON NUMBER(2),
    A_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    VALUATION_APPLICABLE_DATE NUMBER(8),
    A_DATE_PIP_AMOUNT NUMBER(12),
    A_DATE_NPSW_AMOUNT NUMBER(10),
    A_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    A_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    A_DATE_POLICY_VALUE NUMBER(16),
    A_DATE_DATE_PIP_CALCULATED NUMBER(8),
    A_DATE_ALGORITHM_NUMBER NUMBER(2),
    M_DATE_VOTING_VALUE NUMBER(12),
    M_DATE_POLICY_VALUE NUMBER(16),
    E_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    E_DATE_PIP_AMOUNT NUMBER(12),
    E_DATE_NPSW_AMOUNT NUMBER(10),
    E_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    E_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    E_DATE_POLICY_VALUE NUMBER(16),
    E_DATE_DATE_PIP_CALCULATED NUMBER(8),
    E_DATE_ALGORITHM_NUMBER NUMBER(2),
    P_DATE_CASH_OR_BONUS_TYPE CHAR(1 BYTE),
    P_DATE_PIP_AMOUNT NUMBER(12),
    P_DATE_NPSW_AMOUNT NUMBER(10),
    P_DATE_MINIMUM_APPLIED_AMOUNT NUMBER(10),
    P_DATE_MINIMUM_CALC_AMOUNT NUMBER(10),
    P_DATE_POLICY_VALUE NUMBER(16),
    P_DATE_DATE_PIP_CALCULATED NUMBER(8),
    P_DATE_ALGORITHM_NUMBER NUMBER(2),
    SOURCE_EXTRACT_DATE_TIME DATE,
    SCHEME_SEQUENCE_NUMBER NUMBER(3),
    LOAD_FLAG CHAR(1 BYTE),
    STG_CREATE_DATE_TIME DATE,
    STG_UPDATE_DATE_TIME DATE
    TABLESPACE TPDBS01A_DATA
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    CREATE UNIQUE INDEX PK_STG_TL_CS_EXTRACTED_RECS ON TPD_STG_TL_CS_EXTRACTED_RECS
    (RECORD_KEY)
    LOGGING
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    NOPARALLEL;
    ALTER TABLE TPD_STG_TL_CS_EXTRACTED_RECS ADD (
    CONSTRAINT PK_STG_TL_CS_EXTRACTED_RECS
    PRIMARY KEY
    (RECORD_KEY)
    USING INDEX
    TABLESPACE TPDBS01A_DATA
    PCTFREE 10
    INITRANS 2
    MAXTRANS 255
    STORAGE (
    INITIAL 128K
    NEXT 128K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    ));

    I would like to discuss a bit more how a composite index is used. This is not anymore the question of the OP, but I think it will deepen my understanding and maybe that of others as well.
    So we have this situation to start with.
    * A select on two different columns.
    * An index on each column would lead to an INDEX RANGE SCAN because of the where condition.
    * Instead of 2 indexes where only one would be used (not considering bitmap conversions), we add a composite index on both columns.
    * The CBO will choose and access the index.
    Question is: How is this access is done in detail?
    So 400 rows come out of the index range scan.
    This would not be possible if it only scanned one of the two predicates. I agree. The output of the index seem to be only those (400) rows that fit with the where clause on both columns.
    This is supported by the fact that an Index only access is possible when we select only information that is in the index (Oracle 9i output).
    SQL> explain plan for
      2  select record_key
      3  from mytable
      4  where stg_update_date_time >= to_date('2007-11-11','yyyy-mm-dd')
      5  and stg_update_date_time < to_date('2007-11-12','yyyy-mm-dd')
      6  and record_key like 'TP%'
      7  /
    Explained.
    SQL>  select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id  | Operation            |  Name       | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT     |             |   160 |  2400 |     2 |
    |   1 |  INDEX RANGE SCAN    | I1          |   160 |  2400 |     2 |
    Note: cpu costing is off, PLAN_TABLE' is old version
    9 rows selected.
    SQL> Unfortunately I don't see the filter operation, probably because the plan table is old in my system.
    The index is build on columns "stg_update_date_time" and "record_key". So it must access these columns in that order.
    I think, that maybe the range scan is done on the date column and then a further access/filter operation is done to rule out any index entries (leaf nodes) that do not fit with the LIKE 'TP%' expression.
    Since I expect that is is faster to access the data in the index than in the table this should improve performance quite a bit. It is not the same access plan/speed however as with a clause like this:
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id  | Operation                   |  Name       | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT            |             |     1 |   520 |     3 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| MYTABLE     |     1 |   520 |     3 |
    |   2 |   INDEX RANGE SCAN          | I1          |     1 |       |     2 |
    Note: cpu costing is off, PLAN_TABLE' is old version
    10 rows selected.
    SQL> The difference can be seen in the cost estimation.
    I hope somebody does understand what I would like to point at.
    Result of this considerations:
    1) Composite index can be used
    2) The index is used as a range scan on one column and as a filter operation after this access on the second column. This is like an extra select statement inside the index structure.
    3) The resulting table access is as small as possible.
    4) A faster access plan can be achieved when the first column is accessed with direct (unique) scan on the first and a range scan on the second column.
    br Sven
    Message was edited by:
    Sven Weller

  • Help with this query

    eid manager
    1 111
    2 1
    3 2
    4 2
    5 2
    6 3
    7 5
    this is a table and i have to prduce output in the form which employee reports
    to which manager
    like
    row one: 7>5>2>1
    row two 6>3>2>1
    here in row one 7 reports to 5 which report to 2 which reports to 1.
    query should be only in sql no pl/sql.

    For a good discussion on this topic, see:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:2165134263446

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

  • Please help with this query!

    Hi All,
    I have this this table:
    Term Grade
    term_A A
    term_A A
    term_A B
    term_A B
    term_B D
    term_B F
    term_B F
    term_C C
    How do I display so that it appears this way?
    term_A A 2
    term_A B 2
    term_B D 1
    term_B F 2
    term_C C 1
    Thank you. Appreciate all the help!

    Please read about [url http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#sthref962]aggregate functions in the manual.
    Regards,
    Rob.

  • Pls help with this precedure

    when I ran this cursor, I get the right results, the idea is that when an email on this table szcasud_email is diffrent than an email on this table GOREMAL.
    I will deactivate the email on this table
    UPDATE general.goremal
    SET
    goremal_status_ind = 'I'
    Then I will insert the new email that is store on this table szcasud
    This code is not consistent: It works sometimes but not all the time..
    goremal_status_ind = 'I' Inactive email
    goremal_status_ind = 'A' Active email
    PROCEDURE appl_email_update (
    p_user IN VARCHAR2,
    p_update_err_code OUT VARCHAR2,
    p_ora_err_code OUT NUMBER,
    p_ora_err_msg OUT VARCHAR2
    IS
    Modification History
    09/20/2009 Creator:  Changes:
    This precedure will check to see if the email coming in on the supplement is
    different that an existing email in goremal(REC1), if it is, it will deactivate
    the existing one and create a new record with the new email coming in.
    v_out_path VARCHAR2 (40) := 'MIDD_LOG';
    v_out_file VARCHAR2 (40)
    := 'common_app_load_pkg' || TO_CHAR (SYSDATE, 'YYYYMMDDHH');
    v_file_handle UTL_FILE.file_type;
    e_update_zero EXCEPTION;
    v_count NUMBER := 0;
    v_pidm spriden.spriden_pidm%TYPE;
    v_email_address goremal.goremal_email_address%TYPE;
    v_email_address2 goremal.goremal_email_address%TYPE;
    v_emal_code goremal.goremal_emal_code%TYPE;
    CURSOR upd_email_upd_cur
    IS
    SELECT
    DISTINCT
    spriden_pidm,
    REGEXP_REPLACE (szcasud_email,
    '[^0-9a-zA-Z+._@-]',
    NULL
    ),REGEXP_REPLACE(GOREMAL_EMAIL_ADDRESS, '[^0-9a-zA-Z+._@-]',
    NULL
    FROM
    saturn_midd.szcasud,
    saturn.spriden,
    general.goremal
    WHERE spriden_id = szcasud_common_appl_id
    and goremal_pidm = spriden_pidm
    and REGEXP_REPLACE (szcasud_email,
    '[^0-9a-zA-Z+._@-]',
    NULL
    ) <> REGEXP_REPLACE(GOREMAL_EMAIL_ADDRESS, '[^0-9a-zA-Z+._@-]',
    NULL
    AND spriden_ntyp_code = 'CAPP'
    AND GOREMAL_STATUS_IND = 'A'
    and goremal_emal_code = 'REC1';
    BEGIN
    UTL_FILE.fclose_all;
    v_file_handle := UTL_FILE.fopen (v_out_path, v_out_file, 'a');
    UTL_FILE.put_line (v_file_handle,
    CHR (10) || TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS')
    UTL_FILE.put_line (v_file_handle, 'Entering appl_email_update');
    /*In case there are old emails that are different, deactivate the existing one
    before inserting the new one */
    IF upd_email_upd_cur%ISOPEN
    THEN
    CLOSE upd_email_upd_cur;
    END IF;
    OPEN upd_email_upd_cur;
    LOOP
    FETCH upd_email_upd_cur
    INTO v_pidm,v_email_address,v_email_address2;
    EXIT WHEN upd_email_upd_cur%NOTFOUND;
    IF upd_email_upd_cur%FOUND
    THEN
    UPDATE general.goremal
    SET
    goremal_status_ind = 'I',
    goremal_activity_date = SYSDATE,
    goremal_data_origin = 'common_app_load_pkg',
    goremal_user_id = p_user
    WHERE goremal_pidm = v_pidm AND goremal_emal_code = 'REC1';
    END IF;
    COMMIT;
    ---END LOOP;
    INSERT INTO general.goremal
    goremal_pidm,
    goremal_emal_code,
    goremal_status_ind,
    goremal_preferred_ind,
    goremal_activity_date,
    goremal_user_id,
    goremal_disp_web_ind,
    goremal_email_address,
    goremal_data_origin
    SELECT
    DISTINCT
    spriden_pidm,
    'REC1',
    'A',
    'N',
    SYSDATE,
    p_user,
    'N',
    REGEXP_REPLACE (szcasud_email,
    '[^0-9a-zA-Z+._@-]',
    NULL
    -- ),REGEXP_REPLACE(GOREMAL_EMAIL_ADDRESS, '[^0-9a-zA-Z+._@-]',
    --- NULL
    'common_app_load_pkg'
    FROM
    saturn_midd.szcasud,
    saturn.spriden,
    general.goremal a
    WHERE spriden_id = szcasud_common_appl_id
    and a.goremal_pidm = spriden_pidm
    AND a.goremal_pidm = v_pidm
    and REGEXP_REPLACE (szcasud_email,
    '[^0-9a-zA-Z+._@-]',
    NULL
    ) <> REGEXP_REPLACE(a.goremal_email_address, '[^0-9a-zA-Z+._@-]',
    NULL
    AND spriden_ntyp_code = 'CAPP'
    and goremal_emal_code = 'REC1'
    AND goremal_status_ind = 'I'
    AND NOT EXISTS
    (SELECT 1
    FROM
    general.goremal B
    WHERE b.goremal_pidm = a.goremal_pidm
    and b.goremal_emal_code = 'REC1'
    and b.goremal_status_ind = 'A');
    END LOOP;
    COMMIT;
    CLOSE upd_email_upd_cur;
    SELECT COUNT (goremal_pidm)
    INTO v_count
    FROM general.goremal
    WHERE TO_CHAR (goremal_activity_date, 'MM/DD/RRRR') =
    TO_CHAR (SYSDATE, 'MM/DD/RRRR')
    AND goremal_data_origin = 'common_appl_data_pkg';
    IF v_count = 0
    THEN
    RAISE e_update_zero;
    ELSE
    UTL_FILE.put_line (v_file_handle,
    'Number of Records Update' || v_count
    END IF;
    EXCEPTION
    WHEN e_update_zero
    THEN
    ROLLBACK;
    p_update_err_code :=
    'CC_ERROR_MSG: Insert Procedure. ZERO Rows Returned in appl_email_update '
    || '.';
    p_ora_err_msg := SUBSTR (SQLERRM, 1, 2000);
    p_ora_err_code := SQLCODE;
    UTL_FILE.put_line (v_file_handle,
    p_update_err_code
    || CHR (10)
    || 'sqlerrm: '
    || p_ora_err_msg
    || ' / sqlcode: '
    || SQLCODE
    WHEN OTHERS
    THEN
    ROLLBACK;
    p_update_err_code :=
    'CC_ERROR_MSG: Error on UPDATE statement for term ' || '.';
    p_ora_err_msg := SUBSTR (SQLERRM, 1, 2000);
    p_ora_err_code := SQLCODE;
    END appl_email_update;

    maybe I am missing something here but couldn't you just do one update statement and one insert statement instead of a cursor?
    something like for the update part
    merge INTO general.goremal a USING
    ( SELECT DISTINCT spriden_pidm,
      REGEXP_REPLACE (szcasud_email, '[^0-9a-zA-Z+._@-]', NULL ),
      REGEXP_REPLACE(GOREMAL_EMAIL_ADDRESS, '[^0-9a-zA-Z+._@-]', NULL )
    FROM saturn_midd.szcasud,
      saturn.spriden,
      general.goremal
    WHERE spriden_id = szcasud_common_appl_id
    AND goremal_pidm = spriden_pidm
    AND REGEXP_REPLACE (szcasud_email, '[^0-9a-zA-Z+._@-]', NULL ) REGEXP_REPLACE(GOREMAL_EMAIL_ADDRESS, '[^0-9a-zA-Z+._@-]', NULL )
    AND spriden_ntyp_code  = 'CAPP'
    AND GOREMAL_STATUS_IND = 'A'
    AND goremal_emal_code  = 'REC1'
    ) b ON (a.goremal_pidm = b.spriden_pidm AND a.goremal_emal_code = 'REC1')
    WHEN matched THEN
      UPDATE
      SET a.goremal_status_ind  = 'I',
        a.goremal_activity_date = SYSDATE,
        a.goremal_data_origin   = 'common_app_load_pkg',
        a.goremal_user_id       = p_user;and maybe another merge for the insert or just the select you are using just change the
    AND a.goremal_pidm = v_pidmand a.goremal_pidm in (select pidm from blah blah blah)

  • Help with this query please

    Hi there, 
    These are the sample values
    declare @table table
    Name varchar(50),
    flag int
    insert into @table
    values('Matt', 0),
    ('George', 0),
    ('George', 1),
    ('Lucas', 0),
    ('Jerome', 0),
    ('Jerome', 1)
    I want to select out where George and Jerome where flag = 0 but leave the records from the same names where flag = 1. All others that only have flag = 0, should stay. So only the names that repeat and have both flag, flag = 0 zero should be selected out.
    Thanks for your help.

    So desired output is ????
    George 0
    Jerome 0
    declare @table table
    Name varchar(50),
    flag int
    insert into @table
    values('Matt', 0),
    ('George', 0),
    ('George', 1),
    ('Lucas', 0),
    ('Jerome', 0),
    ('Jerome', 1)
    select name,min(flag) flag,count(*) from @table
    group by name
    having count(*)>1
    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

Maybe you are looking for

  • Run time error installing Premiere Pro 2.0

    I am reinstalling a computer for one of my users on an XP PRo system and I get a run time error when installing Premiere PRo 2.0.  I believe this happened the first time I installed as well but I can no longer get support directly from Adobe.  Any he

  • PDF printing using javax.print

    Hi! I need to create an aplication that generates a PDF document and then prints it. For creating the PDF doc, I use the iText package. I have some problems with printing. I don't know how to print the document I generate. Could you give me a hint pl

  • Warning while using KToolBar

    The midlet code compiles alright but when i try to run it this is what i get WARNING: Resource "Rsrc 58898" may be too large. Hotsync may fail. Wrote: c:\J2mewtk\wtklib\devices\PalmOS_Device\testDB.prc after printing this message the Palm OS emulator

  • How do I upgrade to iOS 5 on iPad?

    I am having difficulty upgrading my iPad to iOS 5.  I synched it, but now everything seems to freeze.  Any help is much appreciated.

  • Yahoo mail account is not supporting!

    Yahoo mail account is not supported by mail aplication.