Running total - analytic function

I wanted to get the running total for yr_total column based on acc_num, month, year, month_total

   ACC_NUM      MONTH       YEAR MONTH_TOTAL YEAR_TOTAL
---------- ---------- ---------- ----------- ----------
         1          1       2008          10     10
         1          2       2008          12     22
         1          3       2008           0     22
         1          4       2008          11     33
         2          1       2008          20     20 
         2          2       2008          10     30
         2          3       2008          10     40
         2          4       2008           0     40
         2          5       2008           0     40
         3          1       2008          20     20 
         3          2       2008          10     30
         3          3       2008          10     40
         3          4       2008           0     40
         3          5       2008          20     60
         

Look at the second post Rob, you need a dummy WHEN NOT APPARIES:

when not matched then
insert (acc_num) values (null)

Add at the end of the merger.

Tags: Database

Similar Questions

  • Order of evaluation of analytic function

    Hello

    have question quite like this:

    with

    -This query selects a 'representative' acct_id by Group (about 300 lines in total)

    acct_repres as

    (

    Select distinct acct_id, origin_id, acct_parm_id of

    (

    Select a.*

    source_id

    , dense_rank() over (partition by order source_id by nulls first, acct_id acct_nbr origin_id) as odr

    account a join account_parm on (a.parm_id = ap.acct_parm_id) ap

    )

    where odr = 1

    )

    Select col1

    col2

    , (select accct_id from ar acct_repres where ar.acct_parm_id = t2.acct_parm_id) col3

    , col4 (select count (1) of acct_repres)

    of une_table t1

    Join other_table t2 on (...)

    And here it is. "Acct_repres" subquery returns more than 300 lines when it is run separately. But when it is used in CTE sometimes (depending on the execution plan) she seems to have that one line - the value in the column col4 is '1 ',.

    While the value of col3 is NULL for most of the cases.

    It looks like the the dense_rank function and the State 'where odr = 1' are evaluated at the end.

    When I use the hint to MATERIALIZE the result was the same.

    But when I put the result of account_repres in the dedicated table and use this table instead of CTE output is correct.

    What is a bug? Or I do something wrong?

    PS: my version of db is 11 GR 1 material (11.1.0.7).

    some unorganized comments:

    -analytical functions are evaluated towards the end of the execution ("' the last set of operations performed in a query with the exception of the final ORDER BY clause"- http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm")

    -but still the result of a SQL query must be deterministic, so I think that your results are not an expected behavior

    -the CBO has some problems with common table expressions (http://jonathanlewis.wordpress.com/2012/05/24/subquery-factoring-7/) if they are of great assistance in the structuring of complex queries. In these cases, you can avoid problems by using inline views

    -Your query uses the common table expressions in scalar subqueries and scalar subqueries are also likely to confuse the CBO. In addition, they are executed once for each row in your result set (or at least for each different correlation value) and can have a negative impact on the performance of the queries in many cases. Often, they can be replaced by outer joins.

    -you say that the suspicion of materialization brings you an erroneous result: the indicator object (online) gives you the correct results?

    Concerning

    Martin Preiss

  • Schedule running Total

    Hi experts,

    Need your expert helping hand for one of the reports that I am currently working.
    This report runs every hours 12:00, 13:00... so now and the requirement is to produce hourly running Total of Stock_Shortages.

    From now on, I had an obligation to produce just the hourly figures for which I used the following query

    SELECT
    TO_CHAR (SALES_ORDER_HEADER. SOH_DATE_RELEASED, ' dd/mm/yyyy') as RELEASED_DATE,
    substr (to_char (SALES_ORDER_HEADER. (SOH_TIME_RELEASED, "HH24:MI:SS"), 1, 2) as RELEASED_TIME,
    SOH_CLASS as a CLASS,
    County (SALES_ORDER_HEADER. SOH_ORDER_NO) as Stock_Shortage
    Of
    COM SALES_ORDER_HEADER SALES_ORDER_HEADER
    WHERE
    SOH_STATUS = ' 05 "
    AND SOH_DATE_RELEASED = TRUNC (SYSDATE)
    AND substr (to_char (SALES_ORDER_HEADER. (SOH_TIME_RELEASED, "HH24:MI:SS"), 1, 2) < substr (to_char(sysdate,'HH24:MI:SS'), 1, 2)
    GROUP BY
    TO_CHAR (SALES_ORDER_HEADER. SOH_DATE_RELEASED, ' dd/mm/yyyy'),
    substr (to_char (SALES_ORDER_HEADER. (SOH_TIME_RELEASED, "HH24:MI:SS"), 1, 2).

    How can I change this query to display a running total of the Stock_Shortage at the end of each hour?

    Plssss help...

    post some sample data (INSERT INTO...)

    with CREATE TABLE...

    It must be addressed using the analytical functions, something like

    SUM(stock_shortage) over (order by trunc (datecol, 'hh'))
    
  • A question about the analytical function used with the GROUP BY clause in SHORT

    Hi all

    I created the following table named myenterprise
    CITY       STOREID    MONTH_NAME TOTAL_SALES            
    ---------- ---------- ---------- ---------------------- 
    paris      id1        January    1000                   
    paris      id1        March      7000                   
    paris      id1        April      2000                   
    paris      id2        November   2000                   
    paris      id3        January    5000                   
    london     id4        Janaury    3000                   
    london     id4        August     6000                   
    london     id5        September  500                    
    london     id5        November   1000
    If I want to find which is the total sales by city? I'll run the following query
    SELECT city, SUM(total_sales) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    that works very well and produces the expected result, i.e.
    CITY       TOTAL_SALES_PER_CITY   
    ---------- ---------------------- 
    london     10500                  
    paris      17000            
    Now in one of my books SQL (Mastering Oracle SQL) I found another method by using the SUM, but this time as an analytic function. Here's what the method of the book suggests as an alternative to the problem:
    SELECT city, 
           SUM(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    I know that the analytic functions are executed after the GROUP BY clause has been transformed completely and Unlike regular aggregate functions, they return their result for each line belonging to the partitions specified in the partition clause (if there is a defined partition clause).

    Now my problem is that I do not understand what we have to use two functions SUM? If we only use one only, i.e.
    SELECT city, 
           SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY;
    This generates the following error:
    Error starting at line 2 in command:
    SELECT city, 
           SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
    FROM myenterprise
    GROUP BY city
    ORDER BY city, TOTAL_SALES_PER_CITY
    Error at Command Line:2 Column:11
    Error report:
    SQL Error: ORA-00979: not a GROUP BY expression
    00979. 00000 -  "not a GROUP BY expression"
    *Cause:    
    *Action:
    The error is generated for the line 2 column 11 which is, for the expression SUM (total_sales), well it's true that total_sales does not appear in the GROUP BY clause, but this should not be a problem, it has been used in an analytical function, so it is evaluated after the GROUP BY clause.

    So here's my question:

    Why use SUM (SUM (total_sales)) instead of SUM (total_sales)?


    Thanks in advance!
    :)





    In case you are interested, that's my definition of the table:
    DROP TABLE myenterprise;
    CREATE TABLE myenterprise(
    city VARCHAR2(10), 
    storeid VARCHAR2(10),
    month_name VARCHAR2(10),
    total_sales NUMBER);
    
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'January', 1000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'March', 7000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id1', 'April', 2000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id2', 'November', 2000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('paris', 'id3', 'January', 5000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id4', 'Janaury', 3000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id4', 'August', 6000);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id5', 'September', 500);
    INSERT INTO myenterprise(city, storeid, month_name, total_sales)
      VALUES ('london', 'id5', 'November', 1000);
    Edited by: dariyoosh on April 9, 2009 04:51

    It is clear that thet Analytics is reduntant here...
    You can even use AVG or any analytic function...

    SQL> SELECT city,
      2         avg(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY
      3  FROM myenterprise
      4  GROUP BY city
      5  ORDER BY city, TOTAL_SALES_PER_CITY;
    
    CITY       TOTAL_SALES_PER_CITY
    ---------- --------------------
    london                    10500
    paris                     17000
    
  • Cannot use analytical functions such as lag/lead in odi components 12 c except in the expression

    Hi I am a beginner of ODI 12 c

    I'm trying to get the last two comments made on the product for a given product id. and load them into a target.

    I have a source table something like

    Product SR_NO comments LAST_UPDATED_TS

    1 good car 2015/05/15 08:30:25

    1 car average 2015/05/15 10:30:25

    Jeep 2 super 2015/05/15 11:30:25

    1 car bad 2015/05/15 11:30:25

    Jeep 2 horrible 2015/05/15 09:30:25

    Jeep 2 excellent 2015/05/15 12:30:25


    I want a target table based on their last timestamp updated as (last two comments)


    SR_NO Comment1 Comment2

    1                             bad                      average

    2 super excellent

    I used the logic below to get records in SQL Developer but in ODI 12 c, I'm not able to do this by mapping a source to the target table by applying analytical functions to the columns in the target table. Can someone help me solve this problem

    SELECT * FROM)

    SELECT SR_NO Comment1, LAG(Comment1,1,) ON Comment2 (SR_NO ORDER BY LAST_UPDATED_TS ASC PARTITION),

    ROW_NUMBER() ON RN (SCORE FROM SR_NO ORDER BY LAST_UPDATED_TS DESC)

    FROM Source_table

    ) M

    WHERE RN = 1

    ;

    UM, I'm afraid that ODI puts the filter too early in the request, if it generates:

    SELECT * FROM)

    SELECT SR_NO Comment1, LAG(Comment1,1,) ON Comment2 (SR_NO ORDER BY LAST_UPDATED_TS ASC PARTITION),

    ROW_NUMBER() ON RN (SCORE FROM SR_NO ORDER BY LAST_UPDATED_TS DESC)

    FROM Source_table

    WHERE RN = 1

    ) M

    ;

    Instead of:

    SELECT * FROM)

    SELECT SR_NO Comment1, LAG(Comment1,1,) ON Comment2 (SR_NO ORDER BY LAST_UPDATED_TS ASC PARTITION),

    ROW_NUMBER() ON RN (SCORE FROM SR_NO ORDER BY LAST_UPDATED_TS DESC)

    FROM Source_table

    ) M

    WHERE RN = 1

    ;

    Even by changing the 'run on Hint"of your component of the expression to get there on the source, the request will stay the same.

    I think the easiest solution for you is to put everything before the filter in a reusable mapping with a signature of output. Then drag this reusable in your mapping as the new source and check the box "subselect enabled."

    Your final mapping should look like this:

    It will be useful.

    Kind regards

    JeromeFr

  • Can run us javascript function locally within the amx page?

    Hello

    I am totally new to the features of the MAF, let me just 1 thing right, im familiar with the implementation of javascript as on PHP. For example, (1) you can create a js file in a certain directory of your project as long as you can connect properly. And, on the php page, you link such as)<script type="text/javascript" src="file.js"></script>)to be of use inside of your php page or (2)locally run the javascript function inside your php page such as

    function myFunction(){
      
    Alert("Hello World.");
    }.


    So far what I've done on the tutorial javascript MAF, same case, you need to specify your javascript function inside a .js file and save your js file in your maf function (so that the javascript functions are available and can be called through the java method of AdfmfContainerUtilities.invokeContainerJavaScriptFunction () inside your file of java bean managed). After that, in my case to test the tutorial, I need to create a managed bean method to call the associated javascript function based on my actionlistener to the button that ive created inside my amx page, it didn't work (NOTHING HAPPENED when the button is clicked, as maybe it's because I was wrong by calling the managed bean method or class({viewScope.popupHelperBean.onPopupShowHideAction}). )


    Please follow this tutorial to understand what im referring to topic-> https://blogs.oracle.com/mobile/entry/how_to_open_and_close

    (If someone has already managed to made this javascript tutorial, please inform me so that I can see on my error).


    Now I'm trying a different approach which is to run the javascript locally, it's just that I don't have enough resources that could satisfy my investigation to start with. I met this amx: verbatim terms during my research. Fact amx: verbatim help by running the JavaScript locally.


    Thanks in advance.




    Hello Amey,

    Thanks, I had run successfully the popup alert box based on javascript this tutorial you had linked to me, it seems that I am on the right track on how to run javascript on the page of the amx. Its just that the tutorial I mentioned on my post doesn't seem to work as it should, I'll try to resolve the issues for a while. I just want to share with the community who are new to the MAF and are currently working on the custom javascript on page amx application:

    1. include your js inside your working directory file

    2. Add the javascript code that is personalized to your AMX

    3. create a managedbean and a method that could call the javascript function

    Carefully follow this tutorial as mentioned by Amey have the idea of how the javascript is running on amxpage--> https://blogs.oracle.com/mobile/entry/invoking_custom_javascript_from_an

    By the way, thank you very much Amey.

    Learner90

  • SELECT LINES FROM TOP TO BOTTOM UNTIL RUNNING TOTAL = SOME_VALUE

    In the example below, I will select rows from top until my cumulative total of PAYAMOUNT is less than or equal to 40000

    ID RATE DATE ORGAMNT PAYAMOUNT

    1 3.23 12/12/12 23000,45 13000.00

    2 4.55 30/05/11 40000,55 26000.00

    3 6.78 21/03/14 60000,00 60000.00

    My output table must be

    ID RATE DATE ORGAMNT PAYAMOUNT

    1 3.23 12/12/12 23000,45 13000.00

    2 4.55 30/05/11 40000,55 26000.00

    Appreciate your help.

    Kind regards.

    Hello

    This sounds like a job for the analytical SUM function.

    As you post CREATE TABLE and INSERT statements for your data, I will illustrate using the table scott.emp, which is probably on your system.

    Scott.EMP contains the ename, hiredate and sal columns below:

    ENAME HIREDATE RUNNING_TOTAL SAL

    ---------- ----------- ---------- -------------

    SMITH, 17 December 1980 800 800

    ALLEN 20 February 1981-1600-2400

    February 22, 1981 DISTRICT 1250 3650

    JONES, 2 April 1981 2975 6625

    May 1, 1981 BLAKE 2850 9475

    CLARK 9 June 1981 2450 11925

    13425 1500 08 - Sep - 1981 TURNER

    MARTIN 28-Sep-1981 1250 14675

    5000 17 November 1981 KING 19675

    JAMES 3 December 1981 950 23625

    FORD 3000 3 December 1981 23625

    MILLER, January 23, 1982 1300 24925

    SCOTT on April 19, 1987 3000 27925

    ADAMS, 23 May 1987 1100 29025

    Now, let's say, we want to show that the first lines (in order by hiredate) where the total sal is not more than 10000.  One way to do that would be to use the SUM function to calculate the running_total above column and use running_total in a WHERE clause, the results below:

    ENAME SAL HIREDATE

    ---------- ----------- ----------

    SMITH, 17 December 1980 800

    ALLEN 20 February 1981 1600

    DISTRICT 1250 22 February 1981

    JONES, 2 April 1981 2975

    May 1, 1981 BLAKE 2850

    Here's a way to do it:

    WITH got_running_total AS

    (

    SELECT ename, hiredate, sal

    SUM (sal) over (ORDER BY hiredate) AS running_total

    FROM scott.emp

    )

    SELECT ename, hiredate, sal

    OF got_running_total

    WHERE running_total<=>

    ORDER BY hiredate

    ;

    The subquery is necessary because the analytic functions are calculated after the WHERE clause has been applied.  If we want to use the results of an analytic function in a WHERE clause, you must calculate the function in a subquery (as got_running_total, above).

  • The appropriate to a MAX on an analytical function syntax

    I am trying to apply a MAX function on a function analytically than doing a MAX as well. However, I can't understand the appropriate syntax. That's what I tried:
    SELECT MAX(MAX(t.col1) OVER (PARTITION BY t.col2) AS max_col
      FROM sample_table t;
    When I try to run the above query, I get a 't.col1 is invalid in the select list because it is not contained in an aggregate function or the GROUP BY clause error.

    You must encapsulate the query that has the analytical function in another query and then make the max in the outer query.

  • problem of analytic function

    Hello

    I have a problem using the analytical function: when I run this query

    SELECT TSIUPSITE, TSIUPCEAN, TSIUPDATE, sum (TSIUPCA) TSIUPCA, TSIUPCTVA, TSIUPP4N, TSIUPPIEC,.
    Sum (TSIUPQTE) TSIUPQTE, sum (TSIUPQTEP) TSIUPQTEP, TSIUPMDIU, TSIUPMDar,
    Sum (TSIUPCRIU) TSIUPCRIU, sum (TSIUPCRAR) TSIUPCRAR, trunc (TSIUPDCRE) TSIUPDCRE, trunc (TSIUPDMAJ) TSIUPDMAJ,
    TSIUPUTIL, TSIUPTRT, TSIUPNERR, TSIUPMESS.
    TSIUPTMVT, TSIUPSMAN, TSIUPMOTIF, sum (TSIUPMHT) TSIUPMHT, 0 vtanfisc.
    TSIUPDATEVERIF, TSIUPNSEQ, TSIUPCINV, count (*) over (partition TSIUPSITE, TSIUPCEAN, TSIUP_TRT) CONTA_ARTICOLO
    OF TST_FLIISR_VTEREMART
    WHERE 1 = 1 - TSIUP_TRT = 1
    AND TSIUPDATE = to_date('27082012','ddmmyyyy')
    and TSIUP_NTRX = 172
    AND TSIUPSITE = 10025
    AND TSIUPCEAN = '8012452018825'
    GROUP OF TSIUPSITE, TSIUPCEAN, TSIUPDATE, TSIUPCTVA, TSIUPP4N, TSIUPPIEC,
    TSIUPMDIU, TSIUPMDar, trunc (TSIUPDCRE), trunc (TSIUPDMAJ), TSIUPUTIL, TSIUPTRT, TSIUPNERR, TSIUPMESS,
    TSIUPTMVT, TSIUPSMAN, TSIUPMOTIF, 0,
    TSIUPDATEVERIF, TSIUPNSEQ, TSIUPCINV
    ORDER OF TSIUPSITE, TSIUPDATE;

    I have the error ORA-00979: not an expression GROUP BY related to the area of TSIUP_TRT, infact, if I run it

    SELECT TSIUPSITE, TSIUPCEAN, TSIUPDATE, sum (TSIUPCA) TSIUPCA, TSIUPCTVA, TSIUPP4N, TSIUPPIEC,.
    Sum (TSIUPQTE) TSIUPQTE, sum (TSIUPQTEP) TSIUPQTEP, TSIUPMDIU, TSIUPMDar,
    Sum (TSIUPCRIU) TSIUPCRIU, sum (TSIUPCRAR) TSIUPCRAR, trunc (TSIUPDCRE) TSIUPDCRE, trunc (TSIUPDMAJ) TSIUPDMAJ,
    TSIUPUTIL, TSIUPTRT, TSIUPNERR, TSIUPMESS.
    TSIUPTMVT, TSIUPSMAN, TSIUPMOTIF, sum (TSIUPMHT) TSIUPMHT, 0 vtanfisc.
    TSIUPDATEVERIF, TSIUPNSEQ, TSIUPCINV, count (*) over (partition TSIUPSITE, TSIUPCEAN) CONTA_ARTICOLO
    OF TST_FLIISR_VTEREMART
    WHERE 1 = 1 - TSIUP_TRT = 1
    AND TSIUPDATE = to_date('27082012','ddmmyyyy')
    and TSIUP_NTRX = 172
    AND TSIUPSITE = 10025
    AND TSIUPCEAN = '8012452018825'
    GROUP OF TSIUPSITE, TSIUPCEAN, TSIUPDATE, TSIUPCTVA, TSIUPP4N, TSIUPPIEC,
    TSIUPMDIU, TSIUPMDar, trunc (TSIUPDCRE), trunc (TSIUPDMAJ), TSIUPUTIL, TSIUPTRT, TSIUPNERR, TSIUPMESS,
    TSIUPTMVT, TSIUPSMAN, TSIUPMOTIF, 0,
    TSIUPDATEVERIF, TSIUPNSEQ, TSIUPCINV
    ORDER OF TSIUPSITE, TSIUPDATE;

    I have no problem. Now the difference between the TSIUPCEAN (or TSIUPSITE) and TSIUP_TRT that TSIUP_TRT is not in the Group By clause, but, to be honest, I don't know why I have this problem using using an analytic function.

    Thanks for help

    Hello

    I think that you are not analytic function correctly.

    Analytical functions will be run for each line. Where as Group BY will run for groups of data.

    See example below for you reference.

    Example 1:
    
    -- Below query displays number of employees for each department. Since we have used analytical function for each row you are getting the number of employees based on the department id.
    
    SQL> SELECT e.department_id,count(*) OVER (PARTITION BY e.department_id) cnt_analytic
      2  FROM employees e
      3  WHERE e.department_id IN (10,20,30);
    
    DEPARTMENT_ID CNT_ANALYTIC
    ------------- ------------
               10            1
               20            2
               20            2
               30            6
               30            6
               30            6
               30            6
               30            6
               30            6
    
    9 rows selected.
    
    Example 2:
    
    -- Since I have used GROUP BY clause I'm getting only single row for each department.
    
    SQL> SELECT e.department_id, count(*) cnt_group
      2  FROM employees e
      3  WHERE e.department_id IN (10,20,30)
      4  GROUP BY e.department_id;
    
    DEPARTMENT_ID  CNT_GROUP
    ------------- ----------
               10          1
               20          2
               30          6
    

    Finally, what I'm trying to explain is - if you use the analytical function with the GROUP BY clause, the query will not give the ful menaing result set.

    See below

    SQL> SELECT e.department_id,count(*) OVER (PARTITION BY e.department_id) cnt_analytic, count(*) cnt_grp
      2  FROM employees e
      3  WHERE e.department_id IN (10,20,30)
      4  GROUP BY e.department_id;
    
    DEPARTMENT_ID CNT_ANALYTIC    CNT_GRP
    ------------- ------------ ----------
               10            1          1
               20            1          2
               30            1          6
    
  • Helps the analytic function

    Here is an example of the table data:
    ID    NAME             Start                  
    1     SARA             01-JAN-2006     
    2     SARA             03-FEB-2006     
    3     LAMBDA             21-MAR-2006     
    4     SARA             13-APR-2006     
    5     LAMBDA             01-JAN-2007     
    6     LAMBDA             01-SEP-2007     
    I would get this:
    Name        Start               Stop
    SARA        01-JAN-2006    20-MAR-2006
    LAMBDA      21-MAR-2006     12-APR-2006
    SARA        13-APR-2006     31-DEC-2006
    LAMBDA      01-JAN-2007      <null>
    I tried using partition and run the function but partition name combines all the lines of Sara and Lambda lines into a single group/partition that is not I am trying to get.
    Is there an analytic function or other means to achieve to combine date ranges only when the same person appeared conescutively?
    Thank you.

    This can be easily achieved using tabibitosan:

    First of all, you need to identify 'groups', that each name in the list belongs

    with sample_data as (select 1 id, 'SARA' name, to_date('01/01/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 2 id, 'SARA' name, to_date('03/02/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 3 id, 'LAMBDA' name, to_date('21/03/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 4 id, 'SARA' name, to_date('13/04/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 5 id, 'LAMBDA' name, to_date('01/01/2007', 'dd/mm/yyyy') start_date from dual union all
                         select 6 id, 'LAMBDA' name, to_date('01/09/2007', 'dd/mm/yyyy') start_date from dual)
    select id,
           name,
           start_date,
           lead(start_date, 1, to_date('31/12/9999', 'dd/mm/yyyy')) over (order by start_date) next_start_date,
           row_number() over (order by start_date)
             - row_number() over (partition by name order by start_date) grp
    from   sample_data;
    
            ID NAME   START_DATE NEXT_START_DATE        GRP
    ---------- ------ ---------- --------------- ----------
             1 SARA   01/01/2006 03/02/2006               0
             2 SARA   03/02/2006 21/03/2006               0
             3 LAMBDA 21/03/2006 13/04/2006               2
             4 SARA   13/04/2006 01/01/2007               1
             5 LAMBDA 01/01/2007 01/09/2007               3
             6 LAMBDA 01/09/2007 31/12/9999               3
    

    You can see the group number is generated by comparing the rownumber overall of all lines (in order) with the rownumber of the rowset by name (in the same order) - when there is a gap because another name appears between the two, the group number changes.

    Once you have identified the number of group for each set of rows, it is easy to find the min / max values in this group:

    
    with sample_data as (select 1 id, 'SARA' name, to_date('01/01/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 2 id, 'SARA' name, to_date('03/02/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 3 id, 'LAMBDA' name, to_date('21/03/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 4 id, 'SARA' name, to_date('13/04/2006', 'dd/mm/yyyy') start_date from dual union all
                         select 5 id, 'LAMBDA' name, to_date('01/01/2007', 'dd/mm/yyyy') start_date from dual union all
                         select 6 id, 'LAMBDA' name, to_date('01/09/2007', 'dd/mm/yyyy') start_date from dual),
         tabibitosan as (select id,
                                name,
                                start_date,
                                lead(start_date, 1, to_date('31/12/9999', 'dd/mm/yyyy')) over (order by start_date) next_start_date,
                                row_number() over (order by start_date)
                                  - row_number() over (partition by name order by start_date) grp
                         from   sample_data)
    select name,
           min(start_date) start_date,
           max(next_start_date) stop_date
    from   tabibitosan
    group by name, grp
    order by start_date;
    
    NAME   START_DATE STOP_DATE
    ------ ---------- ----------
    SARA   01/01/2006 21/03/2006
    LAMBDA 21/03/2006 13/04/2006
    SARA   13/04/2006 01/01/2007
    LAMBDA 01/01/2007 31/12/9999
    

    If you want the date to appear as null max, you will need to use a cast or decode to change it - I'll leave that as an exercise for you to do! I'll also let you to find how to get the day before for the stop_date.

  • How to use Group by in the analytic function

    I need to write the Department that has the minimum wage in a row. She must be with analytical function, but I have problem in group by. I can't use min() without group by.

    Select * from (min (sal) select min_salary, deptno, RANK() ON RN (ORDER BY sal CSA, CSA rownum) of the Group of emp by deptno) < 20 WHERE RN order by deptno;

    Published by: senza on 6.11.2009 16:09

    Hello

    senza wrote:
    I need to write the Department that has the minimum wage in a row. She must be with analytic function

    Therefore with an analytic function? Looks like it is a duty.

    The best way to get these results is with an aggregate, not analysis, function:

    SELECT      MIN (deptno) KEEP (DENSE_RANK FIRST ORDER BY sal)     AS dept_with_lowest_sal
    FROM      scott.emp
    ;
    

    Note that you do not need a subquery.
    This can be modififed if, for example, you want the lowest Department with the sal for each job.

    But if your mission is to use an analytical function, that's what you have to do.

    but I have problem in group by. I can't use min() without group by.

    Of course, you can use MIN without GROUP BY. Almost all of the aggregate (including MIN) functions have analytical equivalents.
    However, in this issue, you don't need to. The best analytical approach RANK only, not use MIN. If you ORDER BY sal, the lines with rank = 1 will have the minimum wage.

    Select * from (min (sal) select min_salary, deptno, RANK() ON RN (ORDER BY sal CSA, CSA rownum) of the Group of emp by deptno) WHERE the RN< 20="" order="" by="">

    Try to select plain old sal instead of MIN (sal) and get reid of the GROUP BY clause.

    Add ROWNUM in the ORDER BY clause is to make RANK return the same result as ROW_NUMBER, every time that it is a tie for the sal, the output will still be distinct numbers. which line gets the lower number will be quite arbitrary, and not necessarily the same every time you run the query. For example, MARTIN and WARD have exactly the same salary, 1250. The query you posted would assign rn = 4 to one of them and rn = 5 to another. Who gets 4? It's a toss-up. It could be MARTIN the first time you try, and WARD the next. (In fact, in a very small table like scott.emp, it probably will be consistent, but always arbitrary.) If this is what you want, it would be clearer and simpler just to use ROW_NUMEBR instead of RANK.

  • Apple Watch keeps a running total?

    I do not like the brand "Fitbit" because they have reset every day.  Apple Watch maintains a 'running total' miles I have finished or does it reset every day like the Fitbit?

    Hello

    The total distance is reset every day within the activity app.

    More information:

    Use the activity on your Apple Watch - Apple Support

  • Which analytical function to use?


    Hi gurus,

    DB - Oracle 11 g 2

    I followed the examples of data in the table test_a.

    col1 col2 col3

    -----            -------            --------

    x                 y                   y

    p                 q                  y

    a                b                   y

    p                q                   y

    t                 r                    y

    p                q                   y

    The col3 column is always 'y '. But here's the data p, q, there is repeated 3 times (duplicate) and if this is the case I want to update only the first recordings like "n" col3 it is to say p, q, n. rest will be as it is.

    I am able to get the row_number() for it but not able to do this.

    Select col1, clo2, clo3 row_number() over (partition by col2) arrested by col1 as test_a r_num

    Would it be possible directly by any analytic function?

    Thank you

    SID

    COL4 is logical...

    Something like that?

    with x as)

    Select col1, col2 ' x' 'y', 'y' col3 col4 1 Union double all the

    Select 'p' col1, col2 'q', 'y' col3 col4 2 Union double all the

    Select 'a' col1, col2 'b', 'y' col3 col4 3 of all the double union

    Select 'p' col1, col2 'q', 'y' col3 col4 4 Union double all the

    Select 't' col1, col2 'r', 'y' col3, col4 5 Union double all the

    Select 'p' col1, col2 'q', 'y' col3 col4 6 double

    )

    ---

    Select * from)

    Select x.*,

    ROW_NUMBER() on rn1 (score of col1, col2, col3 col4 sort),

    ROW_NUMBER() on rn2 (partition by col1, col2, col3 col4 desc sorting)

    x

    )

    where rn1 = 1 and rn2 <> 1;

    Understand the logic and simply change SELECT a query to UPDATE...

  • Using the analytic function

    Oracle 11g Release 2

    I'm assuming that the best solution is the use of analytical functions.

    create table test3
    ( part_type_id  varchar2(50)
    ,group_id      number
    ,part_desc_id  number
    ,part_cmt      varchar2(50)
    )
    /
    
    insert into test3 values( 'ABC123',1,10,'comment1');
    insert into test3 values( 'ABC123',1,10,'comment2');
    insert into test3 values( 'ABC123',2,15,'comment1');
    insert into test3 values( 'ABC123',2,15,'comment2');
    insert into test3 values( 'EFG123',25,75,'comment3');
    insert into test3 values( 'EFG123',25,75,'comment4');
    insert into test3 values( 'EFG123',25,75,'comment5');
    insert into test3 values( 'XYZ123',1,10,'comment6');
    insert into test3 values( 'XYZ123',2,15,'comment7');
    commit;
    
    select * from test3;
    
    PART_TYPE_ID           GROUP_ID PART_DESC_ID PART_CMT
    -------------------- ---------- ------------ --------------------
    ABC123                        1           10 comment1
    ABC123                        1           10 comment2
    ABC123                        2           15 comment1
    ABC123                        2           15 comment2
    EDG123                        25          75 comment3
    EDG123                        25          75 comment4
    EDG123                        25          75 comment5
    XYZ123                        1           10 comment6
    XYZ123                        2           15 comment7
    
    9 rows selected.
    
    Desired output:
    
    PART_TYPE_ID           GROUP_ID PART_DESC_ID PART_CMT
    -------------------- ---------- ------------ --------------------
    ABC123                        1           10 comment1 
    ABC123                        2           15 comment1
    XYZ123                        1           10 comment1
    XYZ123                        2           15 comment2
    
    RULE: where one part_type_id has multiple (2 or more distinct combinations) of group_id/part_desc_id
    
    NOTE: There are about 12 columns in the table, for brevity I only included 4.
    
    
    
    

    Post edited by: orclrunner was updated desired output and rule

    Hello

    Here's one way:

    WITH got_d_count AS

    (

    SELECT part_type_id, group_id, part_desc_id

    MIN (part_cmt) AS min_part_cmt

    COUNT AS d_count (*) OVER (PARTITION BY part_type_id)

    OF test3

    GROUP BY part_type_id, group_id, part_desc_id

    )

    SELECT DISTINCT

    group_id, part_desc_id, part_type_id, min_part_cmt

    OF got_d_count

    WHERE d_count > 1

    ;

    Output:

    GROUP_ID PART_DESC_ID MIN_PART_CMT PART_TYPE_ID

    ------------ ---------- ------------ ------------

    ABC123 1 10 comment1

    ABC123 2 15 comment1

    XYZ123 1 10 comment6

    XYZ123 2 15 comment7

    Analytical functions, such as the COUNTY and MIN, many global versions, in addition, it can give the same results.  Use the analytical versions when each row of output corresponds to exactly 1 row of input and the aggregate and GROUP BY version when each line of output corresponds to a group of lines 1 or more input.  In this issue, each line of output appears to be a group of input lines having the same group_id, part_type_id, and part_desc_id (I'm guessing just, this only has never stated), so I used GROUP BY to get 1 row of output for every input lines.

  • Truncate output of analytical function?

    For example this query:

    Select month, sum (tot_sales) monthly_sales,.

    AVG (Sum (tot_sales)) (any order by month

    between 1 above and 1 below) rolling_avg

    orders

    where year = 2001 and region_id = 6

    Group by month;

    gives me an output which includes several decimal places for the rolling_avg column.

    Is there a way to truncate this? I tried to use the rounded outside the analytical function and surely enough, it didn't work. I can't think otherwise.

    You can use an external selection on the result of this query

    select trunc(rolling_avg) from
    ( rolling_avg query);
    

Maybe you are looking for

  • Qosmio G40 with HD - DVD burner against BlueRay

    This is my 1st post. I just got my G40-127, and I wonder. Didn't the community of internatiolnal blow to HD - DVD on the sidewalk and go for Blue-Ray? You is a way to get a Blue-Ray wrighter to my machine or has misunderstood this concept HD-DVD mach

  • Problems with HP Deskjet 3070

    I bought an HP Deskjet printer 3070 all in one series may a year ago.  He started having glitches and developed a split personality because he is not sure whether a copy of HP Deskjet 3070 B 1 series, a series of printer HP Deskjet 3070 B, he is cert

  • Images on the screen are HUGE. Can you help me with this?

    The images on my screen are HUGE. I can't read a page without sweeping left and right.  If I try to play a game, it is impossible, because the game does not appear.  This has happened without any changes to the computer.  In addition, several times w

  • Semicircle of semicircle Illustrator

    Hi everyone, I need to insert a rectangle-shaped semicircle, can someone help me with this?There is the shape of the circle, but if I want to do half a perfect circle?Something like that: http://www.asia.it/adon/files/disegno_heidegger.jpgWithout the

  • How can I disable eject after import in Lightroom 5?

    I had to reimage my computer and now Lightroom 5 ejects my camera memory card automatically after that I have import photos.  He has not done this before.  How do I turn it off?