First_value

Can anyone tell me if there is a more efficient way to do the following........
SELECT distinct accprf.account_id
first_value(accprf.value_start)
over (partition by accprf.account_id order by accprf.start_date) ,
first_value(accprf.value_end)
over (partition by accprf.account_id order by accprf.end_date desc)
FROM account_performance accprf
The table account_performance has more than one row per account_id. Each row has a start date and end date, with account performance information for that time interval. The above gets the values from the very first entry and the very last entry per account_id.
I was expecting to find a less complicated way to do the above.
Thanks, Mario.

Well, in that case it doesn't matter!
This is a little demonstration:
SQL> drop table t;
Table dropped.
SQL>
SQL> create table t (c1 number, c2 number, c3 number);
Table created.
SQL>
SQL> insert into t values (1, 1, 10);
1 row created.
SQL> insert into t values (1, 2, 11);
1 row created.
SQL> insert into t values (1, 3, 7);
1 row created.
SQL>
SQL>
SQL> insert into t values (2, 3, 20);
1 row created.
SQL> insert into t values (2, 4, 21);
1 row created.
SQL> insert into t values (2, 5, 15);
1 row created.
SQL>
SQL> SELECT c1,
  2          SUM(c3) keep (dense_rank first order by c2) sum,
  3          MIN(c3) keep (dense_rank first order by c2) min,
  4          MAX(c3) keep (dense_rank first order by c2) max
  5  FROM t
  6  group by c1;
        C1        SUM        MIN        MAX
         1         10         10         10
         2         20         20         20Message was edited by:
Michel
Sorry,
It have made an implicit assumption that c2 was unique or it is not true and then you are right. It must be min and not max to meet the first query.
Thanks for your correction.

Similar Messages

  • Use of FIRST_VALUE OVER in a PL/SQL query

    Hello,
    Here is my problem:
    I'm trying to execute a query using FIRST_VALUE OVER in a PL/SQL procedure, e.g.
    SELECT FIRST_VALUE (name) OVER (order by birthdate)
    FROM birthday_table
    WHERE location = 'HOME';
    I need to get the value returned. I tried to do it using an INTO clause and
    also with EXECUTE IMMEDIATE, but I get an error like "invalid column name".
    Thank you,
    Olivier.

    Assuming the query runs successfully outside of PL/SQL, the execute immediate construct would be:
    execute immediate 'select first_value ... where location = :loc' into v_some_variable using 'HOME';

  • Replacing Oracle's FIRST_VALUE and LAST_VALUE analytical functions.

    Hi,
    I am using OBI 10.1.3.2.1 where, I guess, EVALUATE is not available. I would like to know alternatives, esp. to replace Oracle's FIRST_VALUE and LAST_VALUE analytical functions.
    I want to track some changes. For example, there are four methods of travel - Air, Train, Road and Sea. Would like to know traveler's first method of traveling and the last method of traveling in an year. If both of them match then a certain action is taken. If they do not match, then another action is taken.
    I tried as under.
    1. Get Sequence ID for each travel within an year per traveler as Sequence_Id.
    2. Get the Lowest Sequence ID (which should be 1) for travels within an year per traveler as Sequence_LId.
    3. Get the Highest Sequence ID (which could be 1 or greater than 1) for travels within an year per traveler as Sequence_HId.
    4. If Sequence ID = Lowest Sequence ID then display the method of travel as First Method of Travel.
    5. If Sequence ID = Highest Sequence ID then display the method of travel as Latest Method of Travel.
    6. If First Method of Travel = Latest Method of Travel then display Yes/No as Match.
    The issue is cells could be blank in First Method of Travel and Last Method of Travel unless the traveler traveled only once in an year.
    Using Oracle's FIRST_VALUE and LAST_VALUE analytical functions, I can get a result like
    Traveler | Card Issue Date | Journey Date | Method | First Method of Travel | Last Method of Travel | Match?
    ABC | 01/01/2000 | 04/04/2000 | Road | Road | Air | No
    ABC | 01/01/2000 | 15/12/2000 | Air | Road | Air | No
    XYZ | 01/01/2000 | 04/05/2000 | Train | Train | Train | Yes
    XYZ | 01/01/2000 | 04/11/2000 | Train | Train | Train | Yes
    Using OBI Answers, I am getting something like this.
    Traveler | Card Issue Date | Journey Date | Method | First Method of Travel | Last Method of Travel | Match?
    ABC | 01/01/2000 | 04/04/2000 | Road | Road | <BLANK> | No
    ABC | 01/01/2000 | 15/12/2000 | Air | <BLANK> | Air | No
    XYZ | 01/01/2000 | 04/05/2000 | Train | Train | <BLANK> | No
    XYZ | 01/01/2000 | 04/11/2000 | Train | <BLANK> | Train | No
    Above, for XYZ traveler the Match? clearly shows a wrong result (although somehow it's correct for traveler ABC).
    Would appreciate if someone can guide me how to resolve the issue.
    Many thanks,
    Manoj.
    Edited by: mandix on 27-Nov-2009 08:43
    Edited by: mandix on 27-Nov-2009 08:47

    Hi,
    Just to recap, in OBI 10.1.3.2.1, I am trying to find an alternative way to FIRST_VALUE and LAST_VALUE analytical functions used in Oracle. Somehow, I feel it's achievable. I would like to know answers to the following questions.
    1. Is there any way of referring to a cell value and displaying it in other cells for a reference value?
    For example, can I display the First Method of Travel for traveler 'ABC' and 'XYZ' for all the rows returned in the same column, respectively?
    2. I tried RMIN, RMAX functions in the RDP but it does not accept "BY" clause (for example, RMIN(Transaction_Id BY Traveler) to define Lowest Sequence Id per traveler). Am I doing something wrong here? Why can a formula with "BY" clause be defined in Answers but not the RPD? The idea is to use this in Answers. This is in relation to my first question.
    Could someone please let me know?
    I understand that this thread that I have posted is related to something that can be done outside OBI, but still would like to know.
    If anything is not clear please let me know.
    Thanks,
    Manoj.

  • Issue with First_value

    Hi,
    I am problem pulling right set of data for the below situation.
    SELECT
    FIRST_VALUE(p1)
    OVER (PARTITION BY workorderid ORDER BY NVL(completeddate,createdate) DESC NULLS LAST) pressure
    FROM HISTORY
    Lets say that result set has values for p1 as no and yes for the same completeddate, then the
    query returns value 'no' because it sorts the data alphabetically.
    all i what is, when the completed date is same for two records then look up create date and give me the value of p1 based on max(create date).
    How do i do that using analytical function?
    Thanks
    Billu

    Sorry, i wasn't clear enough earlier.
    here is my entire query posted :
    SELECT
    m.loannumber,
    w.ordernumber,
    o.spikey clientcode,
    v.id vendorname,
    w.spiworkcode workcode,
    w.department_fk department,
    SUBSTR(w.loantypetermid, 10) loantype,
    TRUNC(w.orderdate) orderdate,
    vw_rhist.wcompleteddate Winterization_Completed_Date,
    CASE WHEN vw_rhist.wintsystemtype = 'HeatingSystemType.Dry'
    THEN 'Dry'
    WHEN vw_rhist.wintsystemtype = 'HeatingSystemType.Steam'
    THEN 'Steam'
    WHEN vw_rhist.wintsystemtype = 'HeatingSystemType.Radiant'
    THEN 'Radiant'
    ELSE NULL
    END System_Type,
    CASE WHEN vw_rhist.pressuretestsystem = 'YesNo.Yes' THEN 'Yes'
    WHEN vw_rhist.pressuretestsystem = 'YesNo.No' THEN 'No'
    ELSE NULL
    END pressuretestsystem,
    CASE WHEN vw_rhist.holdpressure = 'YesNo.Yes' THEN 'Yes'
    WHEN vw_rhist.holdpressure = 'YesNo.No' THEN 'No'
    ELSE NULL
    END holdpressure,
    CASE WHEN vw_rhist.systemwell = 'YesNo.Yes' THEN 'Yes'
    WHEN vw_rhist.systemwell = 'YesNo.No' THEN 'No'
    ELSE NULL
    END systemwell,
    a.state state
    FROM organizationalrole o,
    vendor v,
    serviceableasset s,
    address a,
    mortgage m,
    (SELECT *
    FROM workorder
    WHERE department_fk = 2
    AND loantypetermid IN ( 'LoanType.CDG','LoanType.CV','LoanType.FHA','LoanType.FMC','LoanType.FNM',
    'LoanType.REO','LoanType.UNK','LoanType.VA'))w,
    SELECT workorderid,rnk,wcompleteddate,pressuretestsystem,
    holdpressure,systemwell,wintsystemtype
    FROM
    ((SELECT workorderid,
    RANK() OVER (PARTITION BY workorderid ORDER BY oid) rnk,
    MIN(COALESCE(winterizationdate, completeddate, createdate))
    OVER (PARTITION BY workorderid) wcompleteddate,
    FIRST_VALUE(pressuretestsystem)
    OVER (PARTITION BY workorderid
    ORDER BY NVL(completeddate, createdate) DESC NULLS LAST)
    pressuretestsystem, FIRST_VALUE(holdpressure)
    OVER (PARTITION BY workorderid
    ORDER BY NVL(completeddate, createdate) DESC NULLS LAST)
    holdpressure,
    FIRST_VALUE(systemwell)
    OVER (PARTITION BY workorderid
    ORDER BY NVL(completeddate, createdate) DESC NULLS LAST)
    systemwell,
    FIRST_VALUE(wintsystemtype)
    OVER (PARTITION BY workorderid
    ORDER BY NVL(completeddate, createdate) DESC NULLS LAST)
    wintsystemtype
    FROM vwresulthistory
    WHERE resulttype = 'OrderUpdate'
    AND iswinterized = 'WinterizationCompleted.Yes') vw_rhist1)
    WHERE wCompleteddate >=
    TO_DATE('10/01/2009','MM/DD/YYYY') AND
    wCompleteddate <= TO_DATE('10/6/2009','MM/DD/YYYY')) vw_rhist
    WHERE vw_rhist.rnk = 1
    AND v.objectid = w.vendor_fk
    AND w.ordernumber = vw_rhist.workorderid
    AND w.servicingasset_fk = s.objectid
    AND s.address_fk = a.objectid
    AND o.objectid = w.client_fk
    AND m.objectid = s.primaryloan_fk
    ORDER BY 2
    The problem i have is with the first_value that is in bold. Sometimes I do have two identical completeddate, in that situation, the first_value returns pressuretestsystem sorted aphabetically, say you have two identical completed dates of 12/3/09 and pressuretestsystem values of 'no' and 'yes'. What I get is 'no'.
    In that kind of situations, i want to look up create date and return the latest value (which here is 'yes'). Do i need case statement here?
    Thanks for reading this far.
    Billu.

  • FIRST_VALUE,LAST_VALUE,invalid_identifier

    Hello,
    I am converting the ACCESS scripts to ORACLE sql. There is FIRST function in Access script. I converted in oracle sql language, but oracle gives an error as "invalid identifier" that I can not understand the reason.
    If you will help to solve this problem, I am really really appreciate.
    Access query:
    select
    First([Reporting Comps].COMPCODE) AS Cage,
    Last(IIf([Reporting Comps]![COMPCODE] Is Not Null,[Reporting Comps]![compcode],"")) AS MFR,
    First(COMPANIES.COMPANY_NAME) AS FirstOfCOMPANY_NAME,
    First(COMPANIES.COMPANY_CODE) AS FirstOfCOMPANY_CODE,
    Last(IIf([Reporting Comps_1]![COMPCODE] Is Not Null,[Reporting Comps_1]![compcode],"")) AS 2MFR,
    First(COMPANIES_2.COMPANY_NAME) AS FirstOfCOMPANY_NAME1,
    First([Reporting Comps_2].COMPCODE) AS 3MFR,
    IIf([MFR] Is Not Null,[MFR],IIf([3MFR] Is Not Null,[3MFR],IIf([2MFR] Is Not Null,[2MFR],"Others"))) AS M
    My script for oracle:
    SELECT X,Y,Z,
    FIRST_VALUE(BI_Reporting_Comps.COMPCODE) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) CAGE,
    LAST_VALUE(CASE WHEN BI_REPORTING_COMPS.COMPCODE IS NOT NULL THEN BI_REPORTING_COMPS.COMPCODE ELSE NULL END) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) MFR,
    FIRST_VALUE(COMPANIES.COMPANY_NAME) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) FirstOfCOMPANY_NAME,
    FIRST_VALUE(COMPANIES.COMPANY_CODE) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) FirstOfCOMPANY_CODE,
    LAST_VALUE(CASE WHEN BI_REPORTING_COMPS.COMPCODE IS NOT NULL THEN BI_REPORTING_COMPS.COMPCODE ELSE NULL END) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) MFR2,
    FIRST_VALUE(COMPANIES.COMPANY_NAME) OVER ( ORDER BY IND_AUTO_KEY ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) FirstOfCOMPANY_NAME1,
    CASE WHEN MFR Is Not Null THEN MFR
    WHEN MFR2 Is Not Null THEN MFR2
    WHEN MF3 Is Not Null THEN MFR3
    ELSE 'OTHERS'
    END AS MANUFACTURER
    FROM .............
    GROUP BY
    X,
    Y,
    Z,
    CASE WHEN MFR Is Not Null THEN MFR
    WHEN MFR2 Is Not Null THEN MFR2
    WHEN MF3 Is Not Null THEN MFR3
    ELSE 'OTHERS'
    END
    ORDER BY IND_AUTO_KEY ASC;

    Hello
    I've reformatted your code to make it more readable. When you post code please remember to use the {noformat}{noformat} tag before and after to ensure the formatting is preserved.SELECT BI_INVOICES.REPORTED_IN,
    BI_Invoices.IND_AUTO_KEY,
    BI_Invoices.Invoice,
    BI_Invoices.Customer,
    BI_Invoices."P/N",
    BI_Invoices.Qty_Ship,
    BI_Invoices.Unit_Cost,
    BI_Invoices.Unit_Sell,
    BI_Invoices.Total_Cost,
    BI_Invoices.Total_Sales,
    CASE
    WHEN BI_INVOICES.END_DEST1 '@'--<MISSING OPERATOR
    THEN BI_INVOICES.END_DEST1
    WHEN BI_INV_DEST_REF_1.DEST IS NOT NULL THEN BI_INV_DEST_REF_1.DEST
    ELSE bi_inv_dest_ref_2.destination
    END
    AS End_Dest,
    BI_Invoices.End_App,
    BI_Invoices.Salesperson,
    BI_Invoices.SOD_AUTO_KEY,
    FIRST_VALUE (
    BI_Reporting_Comps.COMPCODE)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    Cage,
    LAST_VALUE (
    CASE
    WHEN BI_REPORTING_COMPS.COMPCODE IS NOT NULL
    THEN
    BI_REPORTING_COMPS.COMPCODE
    ELSE
    END)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    MFR1,
    FIRST_VALUE (
    COMPANIES.COMPANY_NAME)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    FirstOfCOMPANY_NAME,
    LAST_VALUE (
    CASE
    WHEN BI_REPORTING_COMPS.COMPCODE IS NOT NULL
    THEN
    BI_REPORTING_COMPS.COMPCODE
    ELSE
    END)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    MFR2,
    FIRST_VALUE (
    COMPANIES.COMPANY_NAME)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    FirstOfCOMPANY_NAME1,
    FIRST_VALUE (
    BI_Reporting_Comps.COMPCODE)
    OVER (ORDER BY BI_INVOICES.IND_AUTO_KEY
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    MFR3
    FROM QCTL.STOCK
    LEFT JOIN QCTL.PO_DETAIL
    ON QCTL.STOCK.POD_AUTO_KEY = QCTL.PO_DETAIL.POD_AUTO_KEY
    LEFT JOIN QCTL.PO_HEADER
    ON QCTL.PO_DETAIL.POH_AUTO_KEY = QCTL.PO_HEADER.POH_AUTO_KEY
    AND QCTL.STOCK.ORIGINAL_PO_NUMBER = QCTL.PO_HEADER.PO_NUMBER
    LEFT JOIN QCTL.RO_DETAIL
    ON QCTL.STOCK.ROD_AUTO_KEY = QCTL.RO_DETAIL.ROD_AUTO_KEY
    LEFT JOIN QCTL.RO_HEADER
    ON QCTL.RO_DETAIL.ROH_AUTO_KEY = QCTL.RO_HEADER.ROH_AUTO_KEY
    LEFT JOIN QCTL.COMPANIES
    ON QCTL.PO_HEADER.CMP_AUTO_KEY = QCTL.COMPANIES.CMP_AUTO_KEY
    AND QCTL.RO_HEADER.CMP_AUTO_KEY = QCTL.COMPANIES.CMP_AUTO_KEY
    LEFT JOIN BI_REPORTING_COMPS
    ON QCTL.COMPANIES.CMP_AUTO_KEY = BI_REPORTING_COMPS.CMP_AUTO_KEY
    RIGHT JOIN QCTL.STOCK_RESERVATIONS
    ON QCTL.STOCK_RESERVATIONS.STM_AUTO_KEY = QCTL.STOCK.STM_AUTO_KEY
    RIGHT JOIN BI_INVOICES
    ON BI_INVOICES.SOD_AUTO_KEY = QCTL.STOCK_RESERVATIONS.SOD_AUTO_KEY
    LEFT JOIN BI_INV_DEST_REF_2
    ON BI_INVOICES.INVOICE = BI_INV_DEST_REF_2.DESTINATION
    LEFT JOIN BI_INV_DEST_REF_1
    ON BI_INVOICES.INVOICE = BI_INV_DEST_REF_1.INVOICE
    GROUP BY BI_INVOICES.REPORTED_IN,
    BI_Invoices.IND_AUTO_KEY,
    BI_Invoices.Invoice,
    BI_Invoices.Customer,
    BI_Invoices."P/N",
    BI_Invoices.Qty_Ship,
    BI_Invoices.Unit_Cost,
    BI_Invoices.Unit_Sell,
    BI_Invoices.Total_Cost,
    BI_Invoices.Total_Sales,
    CASE
    WHEN BI_INVOICES.END_DEST1 '@' --<MISSING OPERATOR
    THEN
    BI_INVOICES.END_DEST1
    WHEN BI_INV_DEST_REF_1.DEST IS NOT NULL
    THEN
    BI_INV_DEST_REF_1.DEST
    ELSE
    bi_inv_dest_ref_2.destination
    END,
    BI_Invoices.End_App,
    BI_Invoices.Salesperson,
    BI_Invoices.SOD_AUTO_KEY,
    BI_Reporting_Comps.COMPCODE,
    COMPANIES.COMPANY_NAME
    I've marked 2 lines with MISSING OPERATOR.  If you were intending for that to be Not Equal, you need to use the != rather than the "<" and ">" operator.  It's a "feature" of the forum software here.
    Also, what's this bit meant to do?LAST_VALUE (
    CASE
    WHEN BI_REPORTING_COMPS.COMPCODE IS NOT NULL
    THEN
    BI_REPORTING_COMPS.COMPCODE
    ELSE
    END
    You're saying if BI_REPORTING_COMPS.COMPCODE is not null  then use it otherwise use null.  In oracle when you assign '' to a string it is actually set to null.  With that in mind, you could just useLAST_VALUE (BI_REPORTING_COMPS.COMPCODE)

  • First_value in Oracle olap based on non - time dimension

    Hi Experts,
    I am trying to figure out to do first_value kind of calculation in Oracle OLAP.
    Here is the requirement -
    Fact table -
    cust_id valid_flag balance
    1 y 1000
    1 y 1500
    2 N 0
    2 y 2000
    2 y 2500
    If valid_flag ='N' and balance =0, then set balance =0 for other cells for the customer. This needs to be done for all the dimensions.
    Any pointer would be useful.
    Regards, Neelesh

    If the switch is really based on a dimension attribute (named particular_value), then it should be easy to create a derived measure.
    CASE
      WHEN particular_dim.particular_value = 'N'
      THEN 0
      ELSE my_cube.balance
    ENDBut perhaps what you mean is that there is another measure, IS_VALID say, and you need to get the value of IS_VALID for the current cust_id and the member named 'particular_value' of the particular_dim. In this case it would look something like this.
    CASE
      WHEN my_cube.is_valid[particular_dim = 'particular_value'] = 'N'
      THEN 0
      ELSE my_cube.balance
    ENDI expect that neither of the above expressions is right, but it should give you some pointers as to the kinds of tricks you can use.

  • Peformance of First_Value

    Hi ,
    I want to know which of the two queries is better in terms of performance(using first_value or a sub query).
    Let us assume that salary is unique...
    1) select first_value(ename ) over (order by sal) from emp;
    or
    2) select ename from emp where sal = (select min(sal) from emp )
    Thanks,
    Anand

    You are comparing apple with oranges. It is because you are comparing analytical vs aggregate. They are different. Because
    SQL> select first_value(ename ) over (order by sal) from emp;
    FIRST_VALU
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    SMITH
    FIRST_VALU
    SMITH
    SMITH
    SMITH
    SMITH
    15 rows selected.
    SQL> select ename from emp where sal = (select min(sal) from emp);
    ENAME
    SMITHFor more information check this url.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:74525921631614
    Regards
    Raj

  • FIRST_VALUE & LAST_VALUE

    Given the following sample data:
    AverageRate CurrencyDate
    1.0001            2001-09-03
    1.0001            2001-09-04
    1.0002            2001-09-05
    1.0002            2001-09-06
    1.0005            2001-09-07
    1.0005            2001-09-08
    1.0005            2001-09-09
    1.0001            2001-09-10
    1.0002            2001-09-11
    1.0002            2001-09-12
    How can I, using FIRST_VALUE and LAST_VALUE, return the desired output:
    AverageRate From            To
    1.0001            2001-09-03   2001-09-04
    1.0002            2001-09-05   2001-09-06
    1.0005            2001-09-07   2001-09-09
    1.0001            2001-09-10   2001-09-10
    1.0002            2001-09-11   2001-09-12
    I know how to do this using min/max, self joins and row_number() with partition by, but surely with 2012 there is a simpler (and more optimized) solution which only requires one select statement.  Are my expectations too much?

    First_Value, Lag, Lead, ROWS, and RANGE are great additions (Oracle still has more cool analytic functions than SQL server though), but they won't necessarily magically solve all problems.  If your data didn't have the unusual position related duplicates
    (where 1.0002 showed up again later in the list, but is a different group to the first time through), your query might have fit 100 percent nicely into a less complex First_Value scenario.
    Here's a way that takes care of it, that does use new SQL 2012 feature ROWS and also FIRST_VALUE.  The key element is the "ROWS" clause, where we were able to limit the window to rows that occurred BEFORE the current row.  Then FIRST_VALUE
    at the final select statement too.
    Create_Testdata:
    Declare @Tbl table (avgrate decimal(9,4), currdate date)
    Insert @Tbl Select 1.0001, '2001-09-03'
    Insert @Tbl Select 1.0001, '2001-09-04'
    Insert @Tbl Select 1.0002, '2001-09-05'
    Insert @Tbl Select 1.0002, '2001-09-06'
    Insert @Tbl Select 1.0005, '2001-09-07'
    Insert @Tbl Select 1.0005, '2001-09-08'
    Insert @Tbl Select 1.0005, '2001-09-09'
    Insert @Tbl Select 1.0001, '2001-09-10'
    Insert @Tbl Select 1.0002, '2001-09-11'
    Insert @Tbl Select 1.0002, '2001-09-12'
    Lister:
    With L1_RowNums_Lead_Lag as
    Select *
    , row_number() over(order by @@Servername) as RN
    , lead(avgrate) over(order by @@servername) as NextRate
    , lag(avgrate) over(order by @@servername) as PrevRate
    From @Tbl
    , L2_RowFamily as
    Select *
    , case When (Prevrate <> avgrate and NextRate <> Avgrate) then RN
    when NextRate = AvgRate and IsNull(PrevRate, -1) <> AvgRate then RN
    Else NULL
    End as RowFamily
    From L1_RowNums_Lead_Lag
    , L3_RowFamily_Assign as
    Select *
    , case when RowFamily is Null
    Then Max(RowFamily) over(partition by avgrate order by rn Rows between unbounded preceding and current row)
    Else RowFamily
    End as RowFamily_All
    from L2_RowFamily
    , L4_Final as
    Select *
    , first_Value(Currdate) over(partition by RowFamily_all order by RowFamily_all) as FirstCurrdate
    , Last_Value(Currdate) over(partition by RowFamily_all order by RowFamily_all) as LastCurrdate
    From L3_RowFamily_Assign
    Select * from L4_Final /* Where clause has to be in final query */
    where RowFamily is not null
    order by RN;
    Results match your posted desired results.

  • When to use First instead of  First_Value functions

    When would you use the First_Values function instead of First? What's the difference between the two?

    Here are some examples of both in action. Use the analytic function FIRST_VALUE when you don't want to group your records. Use the aggregate function FIRST when you do.
    select
      deptno ,
      hiredate ,
      ename ,
      first_value( ename ) over ( partition by deptno order by hiredate ) first_hired
    from emp
    order by deptno, hiredate ;
        DEPTNO HIREDATE   ENAME      FIRST_HIRE
            10 1981-06-09 CLARK      CLARK
            10 1981-11-17 KING       CLARK
            10 1982-01-23 MILLER     CLARK
            20 1980-12-17 SMITH      SMITH
            20 1981-04-02 JONES      SMITH
            20 1981-12-03 FORD       SMITH
            20 1987-04-19 SCOTT      SMITH
            20 1987-05-23 ADAMS      SMITH
            30 1981-02-20 ALLEN      ALLEN
            30 1981-02-22 WARD       ALLEN
            30 1981-05-01 BLAKE      ALLEN
            30 1981-09-08 TURNER     ALLEN
            30 1981-09-28 MARTIN     ALLEN
            30 1981-12-03 JAMES      ALLEN
    14 rows selected.
    select
      deptno,
      min(ename) keep ( dense_rank first order by hiredate ) as first_hired
    from emp
    group by deptno
    order by deptno ;
        DEPTNO FIRST_HIRE
            10 CLARK
            20 SMITH
            30 ALLEN
    3 rows selected.As far as analytic FIRST_VALUE versus the analytic version of FIRST, FIRST_VALUE has the option to IGNORE NULLS whereas FIRST doesn't.
    select
      deptno ,
      hiredate ,
      comm ,
      first_value( comm IGNORE NULLS ) over ( partition by deptno order by hiredate desc )
        as first_value ,
      min(comm) keep ( dense_rank first order by hiredate desc )
        over ( partition by deptno )
        as first
    from emp
    order by deptno, hiredate ;
        DEPTNO HIREDATE         COMM FIRST_VALUE      FIRST
            10 1981-06-09
            10 1981-11-17
            10 1982-01-23
            20 1980-12-17
            20 1981-04-02
            20 1981-12-03
            20 1987-04-19
            20 1987-05-23
            30 1981-02-20        300        1400
            30 1981-02-22        500        1400
            30 1981-05-01                   1400
            30 1981-09-08          0        1400
            30 1981-09-28       1400        1400
            30 1981-12-03
    14 rows selected.Other than that the two seem functionally equivalent. I prefer FIRST_VALUE over FIRST though because its syntax is more familiar.
    Joe Fuda
    SQL Snippets
    Message was edited by: SnippetyJoe - added third example

  • Query Help required

    HI Experts ,
    Could you please help me in getting below output ,
    My Input Table :
    Number
    Loc_A
    LOC_B
    PARENT_NUMBER
    A-01
    Ind
    Aus
    A
    A-02
    Fra
    NZ
    A
    A-03
    Ind
    SL
    A
    A-04
    USA
    Aus
    A
    A-05
    Pak
    WI
    A
    A-06
    Fra
    Ag
    A
    A-07
    Rus
    Ban
    A
    A-08
    SA
    Ind
    A
    A-09
    Ind
    Ind
    A
    My Required Output
    Number
    Loc_A
    LOC_B
    PARENT_NUMBER
    A-01
    Ind
    Aus
    A
    A-02
    Fra
    NZ
    A
    A-03
    Ind
    SL
    null
    A-04
    USA
    Aus
    null
    A-05
    Pak
    WI
    A
    A-06
    Fra
    Ag
    null
    A-07
    Rus
    Ban
    A
    A-08
    SA
    Ind
    A
    A-09
    Ind
    Ind
    null
    I am comparing each and every record with its previous rows values for column Loc_A and Loc_B and if they are getting matched i m inserting null .
    table structure
    with t as
    (select 'A-01' as Num,'Ind' as Loc_A,'Aus' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-02' as Num,'Fra' as Loc_A,'NZ' as Loc_B,'A' as Parent_Num from dual
    Union all
    select 'A-03' as Num,'Ind' as Loc_A,'SL' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-04' as Num,'USA' as Loc_A,'Aus' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-05' as Num,'Pak' as Loc_A,'WI' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-06' as Num,'Fra' as Loc_A,'Ag' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-07' as Num,'Rus' as Loc_A,'Ban' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-08' as Num,'SA' as Loc_A,'Ind' as Loc_B,'A' as Parent_Num from dual
    union all
    select 'A-09' as Num,'Ind' as Loc_A,'Ind' as Loc_B,'A' as Parent_Num from dual
    select * from t;
    Could you please help ,i have 1000's of rows with this kind of data

    Hi,
    I have tried to create a query, this might help you
    WITH t AS (SELECT 'A-01' AS Num,
                      'Ind' AS Loc_A,
                      'Aus' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-02' AS Num,
                      'Fra' AS Loc_A,
                      'NZ' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-03' AS Num,
                      'Ind' AS Loc_A,
                      'SL' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-04' AS Num,
                      'USA' AS Loc_A,
                      'Aus' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-05' AS Num,
                      'Pak' AS Loc_A,
                      'WI' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-06' AS Num,
                      'Ind' AS Loc_A,
                      'Ag' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-07' AS Num,
                      'Rus' AS Loc_A,
                      'Ban' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-08' AS Num,
                      'SA' AS Loc_A,
                      'Ind' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL
               UNION ALL
               SELECT 'A-09' AS Num,
                      'Ind' AS Loc_A,
                      'Ind' AS Loc_B,
                      'A' AS Parent_Num
                 FROM DUAL)
    SELECT t.num,
           t.loc_a,
           t.loc_b,
           CASE
              WHEN (FIRST_VALUE (LOC_A)
                       OVER (ORDER BY NUM RANGE UNBOUNDED PRECEDING)) IN
                         (LOC_A, LOC_B)
                    OR (FIRST_VALUE (LOC_B)
                         OVER (ORDER BY NUM RANGE UNBOUNDED PRECEDING)) IN
                         (LOC_A, LOC_B)
              THEN
              ELSE
                 t.parent_num
           END
              parent_num
      FROM t
    NUM
    LOC_A
    LOC_B
    PARENT_NUM
    A-01
    Ind
    Aus
    A-02
    Fra
    NZ
    A
    A-03
    Ind
    SL
    A-04
    USA
    Aus
    A-05
    Pak
    WI
    A
    A-06
    Ind
    Ag
    A-07
    Rus
    Ban
    A
    A-08
    SA
    Ind
    A-09
    Ind
    Ind
    Only error I have here is the First Value is showing '-'. I have not got enough time to remove it.
    Regards,
    Adarsh

  • Using '=' to check for NULL column value

    We are currently encountering an issue where 10.1.0.5 is happily accepting a check on a column for a null value with what I have always known to be an invalid syntax.
    For instance:
    select col1 from my table where col1=null
    Although this is wrong and we are working on locating the queries formatted as such, what I am wondering is why is it working on the 10.1.0.5 version but we cannot get the same query to execute on 8i, 9i, 10.2.0...? Is there a flag that can be enabled to allow this compare?

    I am familiar with the correct syntax to be using. What I am looking for is a possible explanation as to why the query below returns the correct results on 10.1.0.5 and returns nothing in all other versions. I would expect the same behavior across all instances. See the two lines in bold "AREA=NULL" and "SUBAREA=NULL"
    SELECT DISTINCT
    UNIQID,
    MGRCOMMENT,
    REQ.CREATED_BY CREATED,
    C2.CNAME DEVELOPER,
    C5.CNAME PRODMGR,
    C3.CNAME ASSIGNED,
    C4.CONTACTID CURRENTUSER,
    ID,
    STATUSNAME,
    REQ.STATUS STATUSID,
    PRIORITYNAME,
    TITLE,
    MAS1.MODULENAME,
    MAS1.AREANAME,
    MAS1.SUBAREANAME,
    MIN1.MODULE,
    MIN2.AREA,
    MIN3.SUBAREA
    FROM REQ,
    PRIORITY,
    STATUS,
    (SELECT FIRST_VALUE(M1.MODULENAME)
    OVER (PARTITION BY REQUNIQID ORDER BY MODULENAME ROWS UNBOUNDED PRECEDING) MODULENAME, FIRST_VALUE(A1.AREANAME)
    OVER (PARTITION BY REQUNIQID ORDER BY AREA ROWS UNBOUNDED PRECEDING) AREANAME, FIRST_VALUE(SA1.SUBAREANAME)
    OVER (PARTITION BY REQUNIQID ORDER BY SUBAREANAME ROWS UNBOUNDED PRECEDING) SUBAREANAME, REQUNIQID
    FROM REQMOD, MOD M1, ARA A1, SBARA SA1
    WHERE M1.MODULEID = REQMOD.MODULE
    AND A1.AREAID = REQMOD.AREA
    AND SA1.SUBAREAID = REQMOD.SUBAREA) MAS1,
    (SELECT FIRST_VALUE(C2.CNAME) OVER (PARTITION BY REQUNIQID ORDER BY CNAME ROWS UNBOUNDED PRECEDING) CNAME, REQUNIQID
    FROM REQ_ASSIGN, CONTACT C2
    WHERE C2.CONTACTID = REQ_ASSIGN.CONTACTID
    AND ASSIGNMENT_TYPE=2) C2,
    (SELECT FIRST_VALUE(C5.CNAME) OVER (PARTITION BY REQUNIQID ORDER BY CNAME ROWS UNBOUNDED PRECEDING) CNAME, REQUNIQID
    FROM REQ_ASSIGN, CONTACT C5
    WHERE C5.CONTACTID = REQ_ASSIGN.CONTACTID
    AND ASSIGNMENT_TYPE=1) C5,
    (SELECT FIRST_VALUE(C3.CNAME)
    OVER (PARTITION BY REQUNIQID ORDER BY CNAME ROWS UNBOUNDED PRECEDING) CNAME, REQUNIQID
    FROM REQ_ASSIGN, CONTACT C3
    WHERE C3.CONTACTID = REQ_ASSIGN.CONTACTID
    AND ASSIGNMENT_TYPE<>2
    AND ASSIGNMENT_TYPE<>1) C3,
    (SELECT DISTINCT REQUNIQID, CONTACTID FROM REQ_ASSIGN WHERE CONTACTID=5) C4,
    (SELECT DISTINCT REQUNIQID, MODULE FROM REQMOD WHERE MODULE=1) MIN1,
    *(SELECT DISTINCT REQUNIQID, AREA FROM REQMOD WHERE AREA=NULL) MIN2,*
    *(SELECT DISTINCT REQUNIQID, SUBAREA FROM REQMOD WHERE SUBAREA=NULL) MIN3,*
    REQCOMMENTS
    WHERE PRIORITY.PRIORITYID = REQ.PRIORITY
    AND STATUS.STATUSID = REQ.STATUS
    AND MAS1.REQUNIQID = REQ.UNIQID
    AND C2.REQUNIQID = REQ.UNIQID
    AND C5.REQUNIQID = REQ.UNIQID
    AND C3.REQUNIQID = REQ.UNIQID
    AND C4.REQUNIQID = REQ.UNIQID
    AND MIN1.REQUNIQID = REQ.UNIQID
    AND MIN2.REQUNIQID = REQ.UNIQID
    AND MIN3.REQUNIQID = REQ.UNIQID
    AND REQCOMMENTS.REQUNIQID = REQ.UNIQID
    AND REQ.PROJECTID = 3;

  • Item Transaction History Report - Calculation for creating 'Running Total'

    Hello
    Using Oracle Discoverer, we have written a report that pulls back all Inventory Transactions (by item number). This report lists both transactions IN (e.g. receipts into the store) and OUT (e.g. issues out from the store).
    Our customer would like an additional column, to represent 'Running Total', to be added to the report. This column needs to capture the running 'On Hand Quantity' for the associated Item, as each transaction (both transactions IN and OUT of store) is displayed.
    For example, if the initial/first transaction for an item was a Receipt of 500, then this column (on the first line) should display 500. If the second transaction for the item was an issue of 15, then this column (on the second line) should display 485. If the third transaction was for an issue of 50, then this column (on the third line) should display 435. If the fourth transaction was for a receipt of 20, then this column (on the fourth line) should display 455 etc etc
    I'm not sure how I'd write a calculation to cater for this (within discoverer) - do you know if this is achievable? Any help would be much appreciated. This would be easy enough to do in Excel, but I'm a bit of a novice when it comes to discoverer(!)
    Many thanks
    Ross

    Hi,
    You can generally do this type of calculation using analytic functions. You would partition by the item number and order by the transaction date in the analytic function. You can use SUM function (with an order by) to get a running total of a column in the report. You can SUM a calculation containing a CASE statement which changes the OUT transactions to a negative number. The SUM function will start at zero, so you then can use FIRST_VALUE function to get the first value for the item which you could then add to the totals.
    Rod West

  • Querying on a value and using that to pull other data in the same query

    I am having some issues pulling the correct data in a query. There is a table that houses application decision data that has a certain decision code in it, WA, for a particular population of applicants. These applicants also may have other records in the same table with different decision codes. Some applicants do NOT have WA as a decision code at all. What I need to do is pull anyone whose maximum sequence number in the table is associated with the WA decision code, then list all other decision codes that are also associated with the same applicant. These do not necessarily need pivoted, so long as I can pull all the records for a person whose highest sequence number is associated with WA and all of the other decision codes for that applicant for the same term code and application number also appear as rows in the output.
    I do not have the rights in Oracle to create tables, so please pardon if this code to make the table is incorrect or doesn't show up here as code. This is not the entire SARAPPD table framework, just the pertinent columns, along with some data to put in them.
    DROP TABLE SARAPPD;
    CREATE TABLE SARAPPD
    (PIDM              NUMBER(8),
    TERM_CODE_ENTRY   VARCHAR2(6 CHAR),
    APDC_CODE         VARCHAR2(2 CHAR),
    APPL_NO        NUMBER(2),
    SEQ_NO             NUMBER(2));
    INSERT INTO SARAPPD VALUES (12345,'201280','WA',1,4);
    INSERT INTO SARAPPD VALUES (12345,'201280','RE',1,3);
    INSERT INTO SARAPPD VALUES (12345,'201280','AC',1,2);
    INSERT INTO SARAPPD VALUES (23456,'201280','RE',1,2);
    INSERT INTO SARAPPD VALUES (23456,'201280','WA',1,3);
    INSERT INTO SARAPPD VALUES (23456,'201280','SC',1,1);
    INSERT INTO SARAPPD VALUES (34567,'201280','AC',1,1);
    INSERT INTO SARAPPD VALUES (45678,'201210','AC',2,1);
    INSERT INTO SARAPPD VALUES (45678,'201280','AC',1,2);
    INSERT INTO SARAPPD VALUES (45678,'201280','WA',1,3);
    INSERT INTO SARAPPD VALUES (56789,'201210','SC',1,2);
    INSERT INTO SARAPPD VALUES (56789,'201210','WA',1,3);
    COMMIT;I have attempted to get the data with a query similar to the following:
    WITH CURR_ADMIT AS
          SELECT   C.SEQ_NO "CURR_ADMIT_SEQ_NO",
                            C.PIDM "CURR_ADMIT_PIDM",
                            C.TERM_CODE_ENTRY "CURR_ADMIT_TERM",
                            C.APDC_CODE "CURR_ADMIT_APDC",
                            C.APPL_NO "CURR_ADMIT_APPNO"
                              FROM SARAPPD C
                              WHERE C.TERM_CODE_ENTRY IN ('201210','201280')
                              AND C.APDC_CODE='WA'
                             AND C.SEQ_NO=(select MAX(d.seq_no)
                                                   FROM   sarappd d
                                                   WHERE   d.pidm = C.pidm
                                                   AND d.term_code_entry = C._term_code_entry)
    select sarappd.pidm,
           sarappd.term_code_entry,
           sarappd.apdc_code,
           curr_admit.CURR_ADMIT_SEQ_NO,
           sarappd.appl_no,
           sarappd.seq_no
    from sarappd,curr_admit
    WHERE sarappd.pidm=curr_admit.PIDM
    and sarappd.term_code_entry=curr_admit.TERM_CODE_ENTRY
    AND sarappd.appl_no=curr_admit.APPL_NOIt pulls the people who have WA decision codes, but does not include any other records if there are other decision codes. I have gone into the user front end of the database and verified the information. What is in the output is correct, but it doesn't have other decision codes for that person for the same term and application number.
    Thanks in advance for any assistance that you might be able to provide. I am doing the best I can to describe what I need.
    Michelle Craig
    Data Coordinator
    Admissions Operations and Transfer Systems
    Kent State University

    Hi, Michelle,
    903509 wrote:
    I do not have the rights in Oracle to create tables, so please pardon if this code to make the table is incorrect or doesn't show up here as code. This is not the entire SARAPPD table framework, just the pertinent columns, along with some data to put in them. You really ought to get the necessary privileges, in a schema that doesn't have the power to do much harm, in a development database. If you're expected to develop code, you need to be able to fabricate test data.
    Until you get those privileges, you can post sample data in the form of a WITH clause, like this:
    WITH     sarappd    AS
         SELECT 12345 AS pidm, '201280' AS term_code_entry, 'WA' AS apdc_code , 1 AS appl_no, 4 AS seq_no     FROM dual UNION ALL
         SELECT 12345,           '201280',                    'RE',               1,             3                 FROM dual UNION ALL
         SELECT 12345,           '201280',                  'AC',            1,          2               FROM dual UNION ALL
    ... I have attempted to get the data with a query similar to the following:
    WITH CURR_ADMIT AS
          SELECT   C.SEQ_NO "CURR_ADMIT_SEQ_NO",
    C.PIDM "CURR_ADMIT_PIDM",
    C.TERM_CODE_ENTRY "CURR_ADMIT_TERM",
    C.APDC_CODE "CURR_ADMIT_APDC",
    C.APPL_NO "CURR_ADMIT_APPNO"
    FROM SARAPPD C
    WHERE C.TERM_CODE_ENTRY IN ('201210','201280')
    AND C.APDC_CODE='WA'
    AND C.SEQ_NO=(select MAX(d.seq_no)
    FROM   sarappd d
    WHERE   d.pidm = C.pidm
    AND d.term_code_entry = C._term_code_entry)
    Are you sure this is what you're actually running? There are errors. such as referencing a column called termcode_entry (starting with an underscore) at the end of the fragment above. Make sure what you post is accurate.
    Here's one way to do what you requested
    WITH     got_last_values  AS
         SELECT  sarappd.*     -- or list all the columns you want
         ,     FIRST_VALUE (seq_no)    OVER ( PARTITION BY  pidm
                                        ORDER BY      seq_no     DESC
                                  )           AS last_seq_no
         ,     FIRST_VALUE (apdc_code) OVER ( PARTITION BY  pidm
                                        ORDER BY      seq_no     DESC
                                  )           AS last_apdc_code
         FROM    sarappd
         WHERE     term_code_entry     IN ( '201210'
                           , '201280'
    SELECT     pidm
    ,     term_code_entry
    ,     apdc_code
    ,     last_seq_no
    ,     appl_no
    ,     seq_no
    FROM     got_last_values
    WHERE     last_apdc_code     = 'WA'
    ;Don't forget to post the results you want from the sample data given.
    This is the output I get from the sample data you posted:
    `     PIDM TERM_C AP LAST_SEQ_NO    APPL_NO     SEQ_NO
         23456 201280 WA           3          1          3
         23456 201280 RE           3          1          2
         23456 201280 SC           3          1          1
         45678 201280 WA           3          1          3
         45678 201280 AC           3          1          2
         45678 201210 AC           3          2          1
         56789 201210 WA           3          1          3
         56789 201210 SC           3          1          2I assume that the combination (pidm, seq_no) is unique.
    There's an analytic LAST_VALUE function as well as FIRST_VALUE. It's simpler (if less intuitive) to use FIRST_VALUE in this problem because of the default windowing in analytic functions that have an ORDER BY clause.

  • Stored Proc's/Packages Help

    Ok all, again, being new to Oracle and trying to do a humble favor for a friend, I've come up with a problem that I'll need help on. Running these steps individually gets me pretty much the result that I'm looking for, minus some basic retooling with TSQL. However, I've tried to format this in the form of either a package/procedure and I just don't believe I'm doing it right. I've been reading the PL-SQL for Dummies, in addition to the latest Oracle 10G PDFs, but as much as I try, I just can't format the package right, even using v_ types and declaring. Below is the code, and even though I've listed tables, this has to be done dynamically and/or processed in memory. I know this may seem simple at best to those of you who understand Oracle, but to me, it's like a square peg in a round hole.
    Would appreciate any and all comments and assistance. Thank you kindly for your perusal of this post (code below):
    --STEP 1:
    create table tbl1 as
    SELECT ps.id1
    ,ps.id2
    ,ps.tdate
    ,NVL(ps.udate, SYSDATE + 1 )
    ,ps.tcode
    ,decode (y.nmtext,
    'name1', 'nm1',
    'name2', 'nm2',
    'name3','nm3',
    'name4','nm4',
    'name5','nm5',
    'name6','nm6',
    'name7','nm7',
    'name8','nm8')
    ,(SELECT COUNT(ps2.id1)
    FROM tblhere ps2
    WHERE ps2.id1 = ps.id1
    AND ps2.id2 = ps.id2
    AND ps2.tdate <= TO_DATE('03/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    AND NVL(ps2.udate, SYSDATE + 1) >= TO_DATE('02/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    GROUP BY ps2.id2) AS o_cnt
    ,(SELECT COUNT(ps3.id1)
    FROM tblhere ps3
    WHERE ps3.id1 = ps.id1
    AND ps3.tcode = ps.tcode
    AND ps3.tdate <= TO_DATE('03/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    AND NVL(ps3.udate, SYSDATE + 1) >= TO_DATE('02/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    GROUP BY ps3.tcode) AS a_cnt
    ,y.ntype as ntype
    FROM tblhere ps
    INNER JOIN tblz y
    ON ps.id2 = y.thisid
    WHERE ps.tdate <= TO_DATE('03/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    AND NVL(ps.udate, SYSDATE + 1 ) >= TO_DATE('02/01/2007 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    AND tcode = 'placedhere'
    AND y.ntype='testing'
    order by id1, tdate
    --STEP 2:
    create table overages (
    Mynum number,
    MyID number)
    --STEP 3:
    insert into overages
    select count(*) as Mynum, id1
    from tbl1
    group by id1
    having count(id1) > 1
    order by id1 desc
    --STEP 4:
    create table tbl2 (
    nums number,
    cid number,
    ogid number,
    adate date,
    rdate date,
    timer number,
    mymode varchar2(10 Byte),
    place varchar2(50 Byte),
    og_cnt number,
    mymode_cnt number,
    namer varchar2(1 Byte))
    --STEP 5:
    insert into tbl2
    select b.mynum, a.id1, a.id2,
    a.tdate, NVL(a.udate, SYSDATE + 1),
    a.tcode, a.nmtext, a.o_cnt,
    a.a_cnt, a.ntype
    from tbl1 a
    inner join overages b
    on a.id1 = b.myid
    order by cid, adate
    --STEP 6:
    merge into tbl2 a
    using (select rwd,
    cid,
    ogid,
    min(rwd) over (partition by cid, adate, rdate) rwd_min,
    adate,
    rdate,
    mymode, place,
    from (select cid, rowid rwd,
    last_value(d1 ignore nulls) over (partition by cid order by rdate range between unbounded preceding and current row) as adate,
    first_value(d2 ignore nulls) over (partition by cid order by rdate range between current row and unbounded following) as rdate
    from (select cid,
    adate,
    rdate,
    case when abs(adate-lag(rdate) over (partition by cid order by rdate))<=1
    then null else adate end d1,
    case when abs(rdate-lead(adate) over (partition by cid order by rdate))<=1
    then null else rdate end d2
    from tbl2))) b
    on (a.rowid=b.rwd)
    when matched then update set a.adate=b.adate, a.rdate=b.rdate
    delete where b.rwd!=b.rwd_min;

    In general you should create the empty tables first as an installation step. Then in your PL/SQL code you would just do inserts, updates etc.
    Also, a package is defined in two parts:
    CREATE OR REPLACE PACKAGE whatever
    AS
        PROCEDURE p
            ( p_someparam INTEGER );
        FUNCTION q
            RETURN BOOLEAN;
    END whatever;
    CREATE OR REPLACE PACKAGE BODY whatever
    AS
        PROCEDURE p
            ( p_someparam INTEGER )
        IS
        BEGIN
            dbms_output.put_line('Hello, World');
        END p;
        FUNCTION q
            RETURN BOOLEAN
        IS
        BEGIN
            RETURN dbms_random.value(0,10) < 5;
        END q;
    END whatever;
    /

  • How to delete the duplicate data in between two distinct rows in SQL?

    Hi,
    I need to identify the duplicate data with two distinct rows. See my data structure below.
    NAME NAME_1 VALUE START_DATE END_DATE FLAG INDEX
    SUR SE 275 13/12/2005 31/12/2010 B 1
    SUR SE 375 A 1
    SUR SE 475 A 1
    SUR SE 275 13/12/2005 31/12/2010 B 2
    SUR SE 375 A 2
    SUR SE 475 A 2
    SUR SE 175 13/12/2006 31/12/2010 B 3
    SUR SE 375 A 3
    SUR SE 475 A 3
    This is my sample data. Here data are duplicate with different index columns. INDEX 1 and 2 contains same group of combination. So i need to identify any one of duplicate combination(i.e INDEX 1 or 2). Can anyone come up with exact solution?
    Thanks

    Try this:
    with test_table as
    (select 'SUR' NAME, 'SE' NAME_1, 275 VALUE, '13/12/2005' START_DATE, '31/12/2010' END_DATE, 'B' FLAG, 1 IND from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 1 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 1 from dual union all
    select 'SUR', 'SE', 275, '13/12/2005' ,'31/12/2010' ,'B', 2 from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 2 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 2 from dual union all
    select 'SUR', 'SE', 175, '13/12/2006', '31/12/2010', 'B', 3 from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 3 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 3 from dual )
    select t.*,
           CASE WHEN START_DATE IS NULL THEN
             first_value(row_number) OVER (PARTITION BY NAME, NAME_1, IND ORDER BY START_DATE)
           ELSE
             row_number
           END row_number
    from (
    SELECT t.*,
           CASE WHEN START_DATE IS NOT NULL THEN
             row_number() over(PARTITION BY NAME, NAME_1,VALUE, START_DATE, END_DATE, FLAG
                               ORDER BY IND)
           END row_number
      FROM test_table t) t
    order by IND, start_dateNote that this is only checking for diferences in the rows where start_date is not null. Do you want to also check if the records where start_date is null it there are differences? If so you can do this:
    with test_table as
    (select 'SUR' NAME, 'SE' NAME_1, 275 VALUE, '13/12/2005' START_DATE, '31/12/2010' END_DATE, 'B' FLAG, 1 IND from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 1 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 1 from dual union all
    select 'SUR', 'SE', 275, '13/12/2005' ,'31/12/2010' ,'B', 2 from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 2 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 2 from dual union all
    select 'SUR', 'SE', 175, '13/12/2006', '31/12/2010', 'B', 3 from dual union all
    select 'SUR', 'SE', 375, null, null, 'A', 3 from dual union all
    select 'SUR', 'SE', 475, null, null, 'A', 3 from dual )
    SELECT t.*,
           MIN(row_number) OVER(PARTITION BY NAME, NAME_1, IND) MIN
      FROM (SELECT t.*,
                   row_number() over(PARTITION BY NAME, NAME_1, VALUE,
                                                  START_DATE, END_DATE, FLAG
                                         ORDER BY IND) row_number
              FROM test_table t) t
    ORDER BY IND,
              start_date;Edited by: Manuel Vidigal on 13/Abr/2009 12:05

Maybe you are looking for

  • Need Logic in sql

    Declare @table table (EMPIID int, NAME VARCHAR(10),Updatedate datetime) INSERT into @table values(111,'Muthu','02/13/2014') INSERT into @table values(222,'Mari','02/14/2014') INSERT into @table values(222,'Raja','02/13/2014') INSERT into @table value

  • How to find interchanged rows in a database table.

    Hi All, Today I encountered a strange problem and as I'm not very good at SQL I'm unable to fix it. So please help me out in fixing this issue. The issue goes like this. I had a table with two columns say x and y. It should allow only values of one p

  • Portfolios: Review, Commenting, and Approval possible?

    Is it possible to do reviewing, commenting, and approval for a PDF portfolio document?  We were wanting to send out our deliverables to a client using the Portfolio feature to create one crisp document with all of our items inside of it, but it seems

  • LSMW - excel file Upload

    Hi, I want to upload the excel file through LSMW, pls let me know how to do this. I have converted the excel file to .csv and .txt file and can upload the fiel, but not able to upload when trying to do with .xls file. Pls let me know. Thanks, Raju Mo

  • Arrows on Curves in reports Programmatically

    Hi, I would like to add some pointers using the arrow on the curves programatically (please refer the attachement) The Curve peaks would change based on the data; hence I would like to get a report where the arrows are can be put for each point along