lag function, part two

Oracle 11.2.0.1.0 SE - one on OL 5.6 x 86-64

Still faced with a LAG.

Given a table like this
create table emp_hist (
     sample_date  date,
     lname   varchar2(10),
     dept    varchar2(10),
     sal     number
     )
;
Table is added every day with
insert into emp_hist (select sysdate,
                       lname,
                       dept,
                       sal
                from emp)
;
Of course, most of the time, most of the employees will have no change from the previous. What I'm trying to do is filtering all the records of 'no change' and get off at only changes... amount of change and when it appeared

Maybe this:
dept         lname        sample_date     sal
----         -----        -----------     -------
10           smith        1-Aug-2012      10000
                          2-Aug-2012      20000

10           jones        5-Aug-2012      50000
                          6-Aug-2012      60000

20           snuffy       4-Aug-2012      30000
                          5-Aug-2012      40000
or (better)
dept         lname        change_date     prev_sal  curr_sal
----         -----        -----------     -------   --------
10           smith        2-Aug-2012      10000     20000 
10           jones        6-Aug-2012      50000     60000
20           snuffy       5-Aug-2012      30000     40000
Wish I could show what I tried so far, but I'm so stuck, I can't even that.

Hello

Looks like:

WITH     got_prev_sal     AS
(
     SELECT       dept
     ,       lname
     ,       sample_date          AS change_date
     ,       LAG (sal) OVER ( PARTITION BY  lname
                                 ORDER BY        sample_date
                     )      AS prev_sal
     ,       sal                AS curr_sal
     FROM       emp_hist
)
SELECT       *
FROM       got_prev_sal
WHERE       prev_sal     != curr_sal
ORDER BY  lname
,            change_date
;

In any application data (or subquery), analytical functions are calculated after the clause WHERE this request has been applied. If you need to use the results of an analytic function in a WHERE clause, calculate the analytical function in a subquery (such as got_prev_sal, above). You can then use the value returned in the WHERE clause (or elsewhere) in the main query.

I hope that answers your question.
If not, post a small example data (instructions INSERT, to go with the CREATE TABLE statement, you have already published) and also publish outcomes from these data.
Point where the above query is to produce erroneous results, and explain, using specific examples, how you get the right results in these places.
See the FAQ forum {message identifier: = 9360002}

Published by: Frank Kulash, August 7, 2012 16:29

Tags: Database

Similar Questions

  • Syn function between two hard disks

    Is there any function of Syn in the Mac OS already has syn function between two hard disks?

    Just checking, do you mean sync?

  • Formatting text in "function of two button dialog box."

    With monitors high resolution, the text in the Panel that displays the function of two dialog button is often small and difficult to read (at least for these old eyes).  Is it possible to format this text?

    Roy

    You can make your own.

    Make a simple Subvi with two buttons and a text indicator. Make windows style 'dialogue' appearance and add some logic (for example an event structure) to flip the button which was pressed.

  • In Oracle lag function

    Hi all

    I want to understand the inner workings of the Lag function in Oracle, which could help to solve my problem.

    I have the table as the structure below.

    P_ID ENTRY_TIMESTAMP SIZE C_ID
    152871 NOVEMBER 15 05.45.00 PM3092
    1529506.00.00 PM 1ST NOVEMBER 151592
    1530606.00.00 PM 1ST NOVEMBER 15192

    Now, when I write a query as below:

    Select the size, CURR_TIMESTAMP TO_TIMESTAMP (TO_CHAR (ENTRY_TIMESTAMP, 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI'),

    TO_TIMESTAMP (TO_CHAR (LAG (ENTRY_TIMESTAMP) OVER (PARTITION BY ORDER BY ENTRY_TIMESTAMP ASC C_ID), 'YYYYMMDDHH24MI'), 'YYYYMMDDHH24MI') LAG_TIMESTAMP

    OF Entry_log

    where ENTRY_TIMESTAMP BETWEEN to_date (1 November 15 18.00.00','DD-MON-YY HH24.MI.) SS') AND to_date (1 November 15 18.00.00','DD-MON-YY HH24.MI.) SS')

    Query will lead to give Lag_timestamp as 06.00.00 PM for size = 1 but will be NULL for size = 15.

    Why is that Oracle will never lag_timestamp = 06.00.00 PM for size = 15.

    Could someone please explain this behavior.

    I'm using Oracle 11 g.

    Thank you

    I had a small mistake in the above query. now, I fixed it

  • Program SQR using a part two (SQRW.exe)

    Team,

    How to activate the program SQR using a part two (SQRW.exe) in any instance of PS? Can I get the steps please?

    Please let us know.

    1 -\bin\sqr\\BINW and create a shortcut of the sqrw in the folder.

    2. you can find target option, enter the lines below and save.

    D:\PT853\bin\sqr\ora\BINW\sqrw.exe-ZIFD:\PT853\sqr\pssqr.ini - fD: \PT853\sqr\ f D:\PT853\sqr-keep - printer: ht

    3. call the shortcut to SQRW by choosing run as Administrator option. You can get SQR button files

  • LAG function alternative queries

    Dear all,

    WITH t AS

    (SELECT 1 AS num, "test1" AS status

    OF THE DOUBLE

    UNION ALL

    SELECT 2 AS num, "test2" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT 3 AS num, "test3" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT the 4 ACEs num, "test4" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT 5 AS num, "test5" LIKE status

    THE DOUBLE)

    SELECT the State, LAG (status 1) OVER (ORDER BY num) AS previous_status

    T

    Please help me to write search above without LAG function like oracle forms10g unsupported feature LAG.

    Hello, you can join the table itself for the results. This will work only if you have a number in ascending order.

    WITH t AS

    (SELECT 1 AS num, "test1" AS status

    OF THE DOUBLE

    UNION ALL

    SELECT 2 AS num, "test2" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT 3 AS num, "test3" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT the 4 ACEs num, "test4" LIKE status

    OF THE DOUBLE

    UNION ALL

    SELECT 5 AS num, "test5" LIKE status

    THE DOUBLE)

    T1.status, t2.status SELECT previous_status

    T t1, t t2

    where t2.num (+) = t1.num - 1

    order of t1.status

    Best regards, Andrei

  • Lag function

    Oracle version: 11.0.2.0.2.0

    Dear all

    I have a question where I am using tables Tab1 and Tab2

    Struncture of tab1 is

    Store_no NUMBER,

    Sell_date DATE

    Sell quantity number,

    number of item_no

    to tab2

    Number of Item_no

    date date1,

    number of item_price

    I need know the total price of the article sold for 2 days (current as previous)

    Select the store, sell_date, item_no, sell_qty * item_price, lag (sell_qty * item_price, 1) on the partition by (store_no, item_no order of sell_date)

    of tab1, tab2

    where tab1.item_no = tab2.item_no

    and sell_date = date1

    Question1) tables have millions of lines... The lag function is causing the query to run for hours...

    Could you please suggest if we capture these sorts of queries where Lag/lead are used.

    Your query does not much sense. Analytical functions are applied to already recovered lines, and since you have sell_date = date1, all you get is one day sales. All you need is:

    Select the store

    Max (sell_date),

    tab1.item_no,

    sum (case sell_date when date1 then sell_qty * end item_price) day_sales_amount,.

    sum (case sell_date when date1 - sell_qty then 1 * item_price end) prev_day_sales_amount

    of tab1.

    tab2

    where tab1.item_no = tab2.item_no

    and sell_date in the fields (date1, date1 - 1).

    Store group,

    tab1.item_no;

    SY.

  • LAG function to get the value of the measurement for parent

    Hello

    I'm interested if there is no function in OLAP DML, which is similar to the function of TROLLING. LAG function returns the measured value for the previous dimension member (or a few members of the back dimension). I would like to know if this function exists which does not return a meaningless measurement for the dimension member value, but the measured value for the parent of the live dimension member.

    Thanks in advance

    Peter

    _parentrel relationship identifies the parent of each Member of the dimension of a hierarchy.

    use:
    the time - dimension
    time_parentrel - Member parent expression
    time_parentrel (time_hierlist 'CALENDAR') - expression for parent along the CALENDAR hierarchy

    Sales - measure
    Sales (Time time_parentrel) - expression returning sales for the parent of the current Member along the existing hierarchy.
    sales (time time_parentrel (time_hierlist 'EXERCISE'))-expression returning the sales for the parent of the current Member along the FISCAL hierarchy.

    You can search the user's Guide the OLAP DML for many examples of the use of the OLAP DML commands/functions/objects in expressions.
    All of these objects are automatically created/maintained while retaining the dimension from the front end (MN).

    For example:
    (11g) OLAP DML users guide notions-> about-> OLAP DML objects given OLAP DML-> objects that support the use of hierarchical Dimensions section.

  • Is it safe call a function of two different thread at the same time?

    For example,.

    Thread1()

    {

    status = my_function();

    }

    Thread2()

    {

    status = my_function();

    }

    int my_function()

    {

    foo;

    return the result;

    }

    I want to call thread1 and thread2 ma_fonction at the same time.

    Call functions simultaneously, in itself and is not a problem at all. Each thread has its own stack of appeal.

    However, you carefully examine the foo part. If you access resources overall (such as hardware devices, global variables or static local variables), or if you make calls to non thread-safe libraries, then you will have to lock the bits of sensitive code with thread locks, ensuring as well as only one thread can access this code at any time.

    Luis

  • Help, please. Word 2010 Professional does not when I do compare function with two documents big word.

    Help, please. When I try to run the function 'Compare' for two large documents in Microsoft Word 2010 professional, the program stops responding.  I have the Professional Windows 7 operating system. The function 'Compare' works with smaller word documents. What can I do to fix?  Thank you

    First try a repair of Office

    For more help post the specific Group Office/Word

  • Questions of DST, part two

    Oracle 11.20.1.0 SE - One
    Oracle Linux 5.6 x 86-64

    Cut to the Chase. Most of our tasks in the Scheduler is set so that start_date, last_start_date, and next_run_date all specify them the zone with a fixed offset. As a result, the first execution after the time change DST, they ran an hour initially, but then calculation for the next execution corrected and they found running at the scheduled time.

    Finally, almost.

    We have two application schemas that have Task Scheduler.

    Jobs in a schema is featured as above.

    But all the work of the other schema to continue to run an hour earlier.

    the above can be seen in the result of this query:
    select
         instance_name
    ,     systimestamp
    from
         v$instance;
    --
    select 
         owner
    ,     job_name
    ,     log_date
    ,     status
    from
         dba_scheduler_job_log
    here   log_date > sysdate - 10
      and   owner not in ('EXFSYS',
                          'ORACLE_OCM',
                          'PERFSTAT',
                          'SYS'
                          )
    order by
         owner
    ,     job_name
    ,     log_date
    ;
    Very easy to simply go to the bottom of the column LOG_DATE and see time to change.

    For my first two questions is - can someone explain the behavior above, in particular the inconsistency in a single schema 'cure' jobs themselves after the first run after the time change, but another schema employment continuing to run an hour earlier.

    I don't know if she's wearing on her or not, but most of the jobs (two patterns) is provided with a local function to "frequency" that uses a decimal representation of the time (ie: WEEKLY(.4583,'SATURDAY'))


    And a second question - what are the things that affect the representation of time zone in the start_date when defining a new job? Our programmer creates / manages jobs using SQL Navigator, and there is no provision in the GUI it to specify a specific time zone or (offset vs name) method to represent a time zone. I read that there are some influences on the client side, but have not restored that right away.

    Try

    SELECT CAST (SYSDATE AS TIMESTAMP WITH TIME ZONE) FROM dual;
    

    you will see the time zone.

    Or a more detailed example

    ALTER SESSION SET TIME_ZONE='Europe/Prague';
    SELECT dbms_scheduler.stime, sysdate, systimestamp, current_timestamp,CAST (SYSDATE AS TIMESTAMP WITH TIME ZONE), CAST (to_date('1.1.2012','dd.mm.yyyy') AS TIMESTAMP WITH TIME ZONE) FROM dual;
    
    ALTER SESSION SET time_zone='Asia/Bangkok';
    SELECT dbms_scheduler.stime, sysdate, systimestamp, current_timestamp,CAST (SYSDATE AS TIMESTAMP WITH TIME ZONE), CAST (to_date('1.1.2012','dd.mm.yyyy') AS TIMESTAMP WITH TIME ZONE) FROM dual;
    
    ALTER SESSION SET time_zone='-6:00';
    SELECT dbms_scheduler.stime, sysdate, systimestamp, current_timestamp,CAST (SYSDATE AS TIMESTAMP WITH TIME ZONE), CAST (to_date('1.1.2012','dd.mm.yyyy') AS TIMESTAMP WITH TIME ZONE) FROM dual;
    

    You can see that DATE to TIMESTAMP WITH TIME ZONE conversion session TIME_ZONE.

  • How to create a function for the function date two

    Hai All

    How can we create a function for the date function two and to return the number of hours between two dates

    For example

    1 January 2010 0815' - '01-jan-2010 1715' and I need to calculate the time between two dates

    How can I create a procedure

    Thanks I advance

    Srikkanth.M

    What have you tried?

    Here is an example (untested):

    CREATE OR REPLACE FUNCTION RETURN_HOURS
    (
            pDateStart      IN DATE
    ,       pDateEnd        IN DATE
    )
    RETURN NUMBER
    DETERMINISTIC
    AS
    BEGIN
            RETURN (pDateEnd - pDateStart) * 24;
    END RETURN_HOURS;
    
  • How to use print screen (part two)?

    The previous thread for the print screen function was marked as read-only and will not allow replies. I tried all the suggestions (PrtScr, CTRL + C + PrtScr, etc.) and then CTRL V in MS Paint, but print screen still does not work on my machine.

    I am running Win 7 on a laptop HP Pavilion 6b32us cv7. I suspect there's a switch somewhere in Win 7 or HP that allows the key to be turned off. I know this because my former employer wouldn't anyone do the print due to HIPAA violations screens. Therefore, the feature has been disabled. Those of us in I.T. provided a third-party software that aloowed do us the same function, but it frees me not for physicians or healthcare staff. If I have to, I'll go out and buy the software. I really need this feature for a class I'm taking.

    Thank you!

    Kurt, welcome to the forum.

    Here is a video to show you how to use the tool captures:

  • ALT TAB and Windows plus button more TAB functions the two has stopped working

    I have windows vista ultimate and my daughter was playing on the computer. Now the Alt tab function and the windows tab function when you hold the windows key and press tab to scroll through your programs no longer works. I searched through the Control Panel, trying to find where and relight them this setting but can't seem to locate. Anyone know how to activate these functions?

    Hello

    Click Start and type services.msc, and then press . Click on continue in the UAC prompt. Scroll and click on the themes service, and then click Start/restart option in the left column. Good luck, Rick Rogers, aka "Crazy" - Microsoft MVP http://mvp.support.microsoft.com Windows help - www.rickrogers.org

  • get my head wrapped around the LAG function

    Oracle 11.2.0.4 Std Ed

    drop table change_hist;

    create table change_hist (file_name varchar2 (30),)

    date of sample_date,

    number of blocks

    );

    insert into change_hist values (to_date('2015-07-01','yyyy-mm-dd'), 'file1', 5);

    insert into change_hist values (to_date('2015-07-02','yyyy-mm-dd'), 'file1', 5);

    insert into change_hist values (to_date('2015-07-03','yyyy-mm-dd'), 'file1', 6);

    insert into change_hist values (to_date('2015-07-04','yyyy-mm-dd'), 'file1', 6);

    insert into change_hist values (to_date('2015-07-05','yyyy-mm-dd'), 'file1', 6);

    insert into change_hist values (to_date('2015-07-01','yyyy-mm-dd'), 'file2', 5);

    insert into change_hist values (to_date('2015-07-02','yyyy-mm-dd'), 'file2', 5);

    insert into change_hist values (to_date('2015-07-03','yyyy-mm-dd'), 'file2', 5);

    insert into change_hist values (to_date('2015-07-04','yyyy-mm-dd'), 'file2', 5);

    insert into change_hist values (to_date('2015-07-05','yyyy-mm-dd'), 'file2', 5);

    insert into change_hist values ('file3', to_date('2015-07-01','yyyy-mm-dd'), 5);

    insert into change_hist values ('file3', to_date('2015-07-02','yyyy-mm-dd'), 6);

    insert into change_hist values ('file3', to_date('2015-07-03','yyyy-mm-dd'), 6);

    insert into change_hist values ('file3', to_date('2015-07-04','yyyy-mm-dd'), 6);

    insert into change_hist values ('file3', to_date('2015-07-05','yyyy-mm-dd'), 6);

    Desired result

    file_name sample_date prev_value curr_value

    File1 2015-07-03 5 6

    File2 2015-07-02 5 6

    My first attempt...

    SQL > select file_name,.

    2 sample_date,

    3 lag (blocks, 1) (order sample_date) as prev_blocks

    4 change_hist;

    FILE_NAME SAMPLE_DA PREV_BLOCKS

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

    July 1, 15 file1

    July 1, 15 5 file3

    July 1, 15 5 File2

    File2 2 July 15 5

    File1 2 July 15 5

    file3 2 July 15 5

    File1 July 3, 15 6

    File2 July 3, 15 6

    file3 July 3, 15 5

    File1 4 July 15 6

    file3 4 July 15 6

    FILE_NAME SAMPLE_DA PREV_BLOCKS

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

    File2 4 July 15 6

    File2 July 5 15 5

    File1 July 5 15 5

    file3 5 July 15 6

    15 selected lines.

    SQL >

    SQL > spo off

      1  select * from (select file_name, sample_date, lag(blocks) over (partition by file_name order by sample_date) prev,
    blocks
      2  from change_hist)
      3* where prev != blocks
    SQL> /                                                                                                             
    
    FILE_NAME                      SAMPLE_DA      PREV    BLOCKS
    ------------------------------ --------- ---------- ----------
    file1                          03-JUL-15          5          6
    file3                          02-JUL-15          5          6                                                    
    

    You know... you need to partition the file name

    Edit: in the interest of beat some people with a force equal regardless of their status, you didn't really know we tell how to achieve these results, so I could refer to the FAQ on how to ask a question

Maybe you are looking for