Misconception about the LAG function's ... functionality?

So I want to look at the value of a column on a current row, and the value of the same column on the most recently entered row, prior to the current. The problem I'm encountering is that for the current row, I'm only interested in those added last month. So, if the record that I'm seeking in the LAG function is prior to last month, it gets rejected from the resultset.
create table check_lag
(filenr number, code varchar2(2), create_date date);
insert into check_lag values (1,'02',to_date('9/5/2008','MM/DD/YYYY')); -- current
insert into check_lag values (1,'01',to_date('9/1/2008','MM/DD/YYYY')); --lag record, same month
insert into check_lag values (2,'02',to_date('9/10/2008','MM/DD/YYYY'));-- current
insert into check_lag values (2,'01',to_date('8/10/2008','MM/DD/YYYY'));-- lag record prior monthSo this query's results made sense
SELECT FILENR, CODE,
       LAG( CODE ) OVER( PARTITION BY FILENR ORDER BY FILENR, CREATE_DATE ) AS PRIOR_CODE,
       CREATE_DATE
FROM   CHECK_LAG;
FILENR CODE PRIOR_CODE CREATE_DATE
1      01              9/1/2008
1      02   01         9/5/2008
2      01              8/10/2008
2      02   01         9/10/2008But as soon as I add a WHERE clause which set's a boundary around last month, I exclude a LAG record
SELECT FILENR, CODE,
       LAG( CODE ) OVER( PARTITION BY FILENR ORDER BY FILENR, CREATE_DATE ) AS PRIOR_CODE,
       CREATE_DATE
FROM   CHECK_LAG;
FILENR CODE PRIOR_CODE CREATE_DATE
1      01              9/1/2008
1      02   01         9/5/2008
2      02              9/10/2008I know that I could push this into an inline view, and provide the WHERE clause with the date range after the inline view is processed, but this is a huge table with an index on the CREATE_DATE, and so the following forces a table scan
SELECT *
FROM   ( SELECT FILENR, CODE,
                LAG( CODE ) OVER( PARTITION BY FILENR ORDER BY FILENR, CREATE_DATE ) AS PRIOR_CODE,
                CREATE_DATE
        FROM   CHECK_LAG )
WHERE  CREATE_DATE BETWEEN TO_DATE( '09/01/2008', 'MM/DD/YYYY' )
                       AND TO_DATE( '09/30/2008 23:59:59', 'MM/DD/YYYY HH24:MI:SS' )
AND    PRIOR_CODE IS NOT NULL;
FILENR CODE PRIOR_CODE CREATE_DATE
1      02   01         9/5/2008
2      02   01         9/10/2008Is that just the way things are, or am I missing out on another approach?
Thanks,
Chuck

Hi, Chuck,
Thanks for including the CREATE TABLE and INSERT statements.
When you use" ORDER BY <single_column>" in an analytic function, you can restrict it to a range of values relative to the ordering value on the current row.
For example, you could say
ORDER  BY create_date
RANGE  BETWEEN  60 PRECEDING
           AND  30 PRECEDINGif you only wanted to consider rows that were no more than 60 days earlier, but at least 30 days earlier.
It's a little more complicated for your problem, because you can't just hard-code numbers like 60 and 30; you have to compute them for every row.
SELECT     filenr
,     code
,     LAST_VALUE (code) OVER
     ( PARTITION BY     filenr
       ORDER BY     create_date
       RANGE BETWEEN     create_date - ADD_MONTHS ( TRUNC ( create_date
                                    , 'MM'
                               , -1
                               )     PRECEDING
          AND     create_date - TRUNC ( create_date
                             , 'MM'
                             )          PRECEDING
     ) AS prior_code
,     create_date
FROM     check_lag;You could probably get the same results using LAG, but this is exactly for what LAST_VALUE was designed.
Windowing is described in the [SQL Language Reference manual|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/functions001.htm#sthref972] in the section for "analytic functions" in general.

Similar Messages

  • Need details about the Snap to Grid function

    I wanted to repair a problem in a guitar track, So I opened a new track and recorded over the problem. I though that with the Snap to Grid function I could slide the new version on the old track without having to worry about the region moving horizontally. That's what's happening, it is impossible to move the track without changing the timing of the track.
    Is it normal?
    Thanks in advance

    Install freeware hardware diagnostic software like for example SANDRA Sisoft, Everest Home Edit or HWiNFO32.
    Such tools provide you all essential information about the built in parts and the HDD controller.
    Please post some feedback would be interesting to know what SATA controller details would be reported by such tool.

  • Questions about the High Throughput Math Functions

    Hello,
    i am just trying to unterstand what advandages the High Troughput Math Funtions have. So i have to ask some Questions.
    I always talk about beeing inside a SCTL.
    1. In the Image you can see four Add Functions. One with U32 which should use more Ressouces than the one with the U16Datatype which uses mor than the U8. But does my FXP High Througput Math Function use less Ressources than the U8 Version?
    2. Which of this four Add Functions will take less time for Execution?
    3. If I would Add two 32bit Numbers one with the normal Add and one with the High Throughput Add. Which of the Functions will use less Resources and which will be faster?
    4. How would it bee if i had a Multiplication instead? When i unterstand the concept of a Multiplication right it will be done with a DSP48E. This Logic Block is able of Multiplying a 25bit Number with a 18bit Number. So the U32 Multiply will use 2 DSP48Es and the other three Functions would use one DSP48E.
    I guess the U32 Version will have the slowest Execution?
    Whats about the other three will their execution speed be equal or will the Versions with smaller Datatypes be faster?
    With kind regards
    Westgate
    Solved!
    Go to Solution.

    I don't see a big rush to answer this, so I'll give it a shot:
    1. The HT version uses less resources, but only because it is configured with the smallest data types. You should get exactly the same results with the same data types and an Add function. The only difference with the HT version is the ability to specify an output register, and the handshaking signals that account for that delay. IF the add is implemented in a DSP48, the integrated register can result in better timing, but in practice it is usually equivalent to an Add function followed by a feedback node.
    2. The actual delay through an add is proportional to the number of bits, where the critical path is the sequentially computed carry chain. So you could run the last one at the highest clock rate. The FPGA has dedicated fast carry logic, so the difference isn't too significant.
    3. The first one will be VERY slightly smaller and faster, just because you're computing one extra output bit on the second one.
    4. I would expect the speed to depend only on the number of DSP48s used, so the last 3 should be similar. You'd be likely to see different results in practice, though, due to routing differing numbers of bits to registers for the indicators. This assumes you're not taking advantage of any of the pipelining configuration options in the HT Multiply. Those options, and the associated handshaking signals, are really what differentiates the HT versions from the regular numeric functions. They allow you to achieve higher clock rates and throughput at the expense of latency (ie, it will take more clock cycles to produce a valid result but you can get more data through the function in a given amount of time).
    Caveats: All your examples have constant inputs, so the LabVIEW compiler and/or Xilinx tools can and will optimize them to no ops. Small multiplies, multiplies with one constant input, or those just larger than 25x18 may also use some non-DSP48 logic for all or part of the implementation. Note that the HT palettes provide a DSP48E function in case you want control over exactly how a multiply and/or add gets implemented. Placing and routing can result in unexpected behaviors, so estimating timing is much more difficult than simply adding up component delays.

  • Common misconceptions about the role of IT?

    Snufykat wrote:
    If it plugs in to the wall it is IT's responsibility, common misconception.
    You mean the coffee pot isn't IT's responsibility. :)

    With the breath of responsibilities rolled into the job description of an IT pro, it's common for non-IT colleagues to lack a true understanding of what IT is there for.I'm trying to find out about some of the common misconceptions regarding the role of IT within organizations. Can you help shed some light on the following?What odd requests clearly outside your scope of work have you received?Are there any recurring themes in helpdesk tickets that are out of your scope of work/responsibility?Is there anything you must consistently remind your non-IT colleagues about regarding the scope of your role?What isa part of your role that most people have no idea about?Any other fun tidbits on this topic you'd like to share?Thank you in advance for your insight!
    This topic first appeared in the Spiceworks Community

  • Question about the "Create Web Gallery" function in Bridge

    I created a beautiful Web Gallery using Bridge's built-in function which creates a Photoshop Web Gallery.
    Everything works great except for one thing. When I click the "E-Mail Feedback" button, Apple Mail loads and creates blank e-mail message. This is all good, but for some reason the address line is loading up with data instead of just an e-mail address. I was hoping someone versed in html could tell me what I'm doing.  The source code in ThumbnailFrame.html looks like this:
    function sendFeedback(picName) {
    checkForUnSavedChanges(picName);
    var prefix = "mailto:[email protected]";
    var name = null;
    name = prompt("Enter Your Name:", "Your Name");
    if (name) {
    prefix += "subject=" + escape("Feedback from " + name);
    prefix += "&body=";
    var str = ""
    for (var i in feedback) {
    str += i + " ~~ \n";
    str += (feedback[i].approved == true) ? "Approved ~~ \n" : "";
    str += (feedback[i].other == true) ? "Other ~~ \n" : "";
    str += (feedback[i].comments != "") ? ("\nComments:\n" + feedback[i].comments + " ~~ \n") : "";
    str += "____________________________________________\n\n";
    The address line in the Apple Mail message looks like this:    [email protected]=Feedback from Paul Kirtley&body=
    I want it to look like this:  [email protected]
    By looking at the source code above, can someone tell me how I can make an adjustment to keep "subject=Feedback from Paul Kirtley&body=" out of the address line?
    Thanks!

    There are update and insert methods under the "core" section/
    See this image : http://www.oracle.com/technology/obe/obe1013jdev/10131/10131_ejb_30/images/b20105.gif
    You might want to follow this tutorial to see how it works:
    http://www.oracle.com/technology/obe/obe1013jdev/10131/10131_ejb_30/ejb_30.htm#t4

  • One question about the MouseListener and Copy function.

    Hola,
    I want my program to activate a method when the user press left mouse button, but in other window, in other program. I can make it with the Listener, but only when the window of my java program is active. I want to my program to listen for pressing a mouse in other window. And my second question is that I want to make the function like copy - the same, if I am in other window. For example if I have marked one fail to generate copy to the clipboard. Is that possible.
    Thanks.

    Tersit wrote:
    I want my program to activate a method when the user press left mouse button, but in other window, in other program. I can make it with the Listener, but only when the window of my java program is active. I want to my program to listen for pressing a mouse in other window. Your best bet to listen for activities in other non-Java programs is to use a programming language that gets closer to the OS such as C/C++.
    And my second question is that I want to make the function like copy - the same, if I am in other window. For example if I have marked one fail to generate copy to the clipboard. Is that possible.I'm not clear on this. What do you mean by "marked one fail"?

  • Complete doc about Oracle's Builtin Extension Functions

    Hola a Todos:
    where i can found a complete documentation about the oracle builtin extension function that v2 parser would use? in the parser docs and in http://technet.oracle.com/xml, there are only 2 functions referenced with a no very clear explanation about what i can do with.
    Can you give a more complete reference or point me to the right url?
    Thanks in advance
    Saludos,
    gnacio J. Ortega

    Hola Steve:
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Steven Muench ([email protected]):
    Presently, yes.
    What functionality described there is not working properly for you?<HR></BLOCKQUOTE>
    I'm trying to use the ora:output for construct various result tree files with only one xsl file,
    ? is this the way to do that ?
    another try converting a document fragment to a nodeset using ora:node-set, i've try an expresion like :
    <xsl:apply-templates select="ora:node-set(PageStruct:get($ps))"
    the PageStruct namesspace is a extension of my own ( do you remember ) and the function return a document fragment..
    Saludos Ignacio J. Ortega
    null

  • How can i print the description about the field?

    dear folks
    i want to develop a report in that i want to display all fields in MM03 for all views.
    there i want to display first Field description (not field name), then field value.
    ie, for MATNR:
    Material Number = xxxx (value)
    for SPART:
    Division = d1.
    how can i print the description about the field?

    CALL FUNCTION 'DDIF_FIELDINFO_GET'
        EXPORTING
          tabname        = 'MARA'
          FIELDNAME  = 'MATNR'
        TABLES
          dfies_tab      = t_dfies
        EXCEPTIONS
          not_found      = 1
          internal_error = 2
          OTHERS         = 3.
    you will get all the info for the field in t_dfies in that u have the field description also
    run the above FM from se37 and pass tabname = MARA and fieldname = MATNR
    see the results in DFIES_TAB in internal table

  • A question about the option Reset All Settings

    Hello, I have a question about the reset all settings function in the IPad. I need to keep all of the installed applications on the device yet I need to remove any log in information and contacts. Is this the correct option or would the Erase All Content and Settings be what I want?

    If you read the OP's request, they "need to keep all of the installed applications on the device".  Selecting "Erase All Content and Settings" will do just that, erase everything.
    Faroff, you can remove accounts in Settings/ Mail, Contacts, Calendar ... that would remove contacts only if the contacts were synced to such an account.  If contacts were synced from iTunes, you'd have to un-sync them from iTunes by changing the sync settings.  If the contacts were just manually entered and not synced with anything, you have to delete them one by one.  However, iOS will remember past usage of a contact, so even if you remove them they may be recalled by you initiating an email or iMessage to something close to what used to be in the Contacts app.  The only way to clear that I think is to do a full erase of the iPad.
    As for log-in information, go to Settings/ Safari/ Passwords & Autofill, where you can erase passwords and saved credit card info.  You can also clear cookies and data in this menu.
    You might be better off doing a full erase of the iPad.  Why do you not want to remove the apps?  You can re-sync them from iTunes or re-download them if necessary.  Or did you inherit this device from someone else and you're wanting to keep their apps installed but remove their private information?

  • I get an error when starting firefox on several user profiles: the bookmarks and history are not functional something about the file being in use.

    Windows Server 2008 R2, Windows 7 workstations, the appdata folder is redirected to a network share at \\server\profiles and several users are unable to use bookmarks getting an error about the file being in use. I'm wondering if maybe my antivirus (Trend Micro) or my backups (Symantec) might be locking up the places.sqlite for these users? Though I don't understand why it would be for some users and not others. I can't be the first one and I'm not coming up with anything searching google endlessly. Anybody else run into this?

    hello, yes this is likely caused by an external program locking access to the bookmarks/history database. you could try renaming the file in question & see if it is working when it is regenerated, this will clear bookmarks and the history though, so keep a backup...
    [[Fix "The bookmarks and history system will not be functional" error message]]
    http://kb.mozillazine.org/Bookmarks_history_and_toolbar_buttons_not_working_-_Firefox

  • Using the LAG function

    Hi all,
    using: Oracle9i Enterprise Edition Release 9.0.1.3.
    I have a table that looks basically like this:
    SQL> select labour_rate_id, organisation_id, commence_date_time, termination_date_time, labour_rate
      2    from labour_rate
      3  where organisation_id = 3265022
      4  order by commence_date_time;
    LABOUR_RATE_ID ORGANISATION_ID COMMENCE_ TERMINATI LABOUR_RATE
              7095         3265022 20-APR-05 30-OCT-07        43.5
              9428         3265022 01-JAN-06 31-DEC-07        43.5
             10762         3265022 01-NOV-07 31-DEC-08       55.52As you can see with the first organisation, some of the dates overlap - i.e. the second last termination date is between the start and end dates of the last record.
    I'm writing an update statement to make the previous termination date, one day less than the current commence date.
    I cannot rely on the labour rate Id to provide any sequence, it's just a coincidence that these are in order. I can rely on the commence date to be accurate.
    here's what I have so far:
    select * from (select organisation_id,
                          labour_rate_id,
                          commence_date_time,
                          termination_date_time,              
                          lag(labour_rate_id) over (order by organisation_id, commence_date_time) as prev_labour_rate_id,
                          lag(termination_date_time) over(order by organisation_id, commence_date_time) as prev_term_date_time
                     from labour_rate)      
    where prev_term_date_time between commence_date_time and termination_date_timethis should select all those where the previous termination date is between the start and end date of the current one. the only obvious problem with this is:
    LABOUR_RATE_ID ORGANISATION_ID COMMENCE_ TERMINATI LABOUR_RATE
             10742         4406709 01-NOV-06 31-DEC-07          40
             10743         4406711 18-DEC-06 31-DEC-07          46
             10750         4415820 31-OCT-07 31-DEC-08        4.75most of the data is like this. I only want to get the non-contiguous dates for each organisation ID. the above query will pick up these rows due to the lag function not taking into account distinct organisation ID's.
    this works:
    select  lrp.labour_rate_id,
            lrp.organisation_id,       
            lr.commence_date_time,
            lr.termination_date_time,
            lrp.labour_rate_id as prev_labour_rate_id,
            lrp.termination_date_time as prev_term_date_time
       from labour_rate lr,
            labour_rate lrp
      where lrp.organisation_id = lr.organisation_id
        and lrp.commence_date_time = (select max(commence_date_time)
                                    from labour_rate lrs
                                   where lrs.organisation_id = lr.organisation_id
                                     and lrs.commence_date_time < lr.commence_date_time
        and lrp.termination_date_time > lr.commence_date_timebut it makes me cringe. there surely is a more elegant way of doing this?
    ultimately I want to be able to set the termination date equal to the day before the subsequent commencement date for the same organisation where the termination date is between the subsequent commencement and end dates.
    would someone be able to point me in the right direction?

    Well, for a start
    lag(labour_rate_id) over (order by organisation_id, commence_date_time)should be
    lag(labour_rate_id) over (partition by organisation_id order by commence_date_time)

  • Some question about the renegotiation function in SRM Contract (GOA)

    Hi All Expert,
    We are on SRM 5/4.6,  there is a question about the renegotiation function in SRM GOA.
    Can we renegotiate the price for some parts in the GOA items with this function ( e.g. Only renegotiate one item in the contract) ?
    Will the item price updated automatically after the renegotiation?
    Many thanks in advance!!!
        Wendrin

    Hi Sanjeev,
    Many thanks for your help.
    One more question, if I add a new item when we renegotiation, will it be transfered to contract and create a new item after that?
    Thanks and best regards
    Wendrin

  • TS2446 Hi,  had the disabled message this morning, but nervous about the reset function as asking me for my full debit card details.  Will change passwords regardless, but is this a scam or not?

    Had the disabled message on my email this morning.  Nervous about the reset function as asking for bank details.  Is this a scam?
    Thanks

    Hi,
    thanks for the comments and help guys.
    the email address i received from is this one "[email protected]",
    Which I would assume to be ok, but it is the payments link that I'm concerned about.  Wanting bank sort codes, security number, etc.  really not comfortable giving that out to anyone at any time

  • Question about the function module (RFC_READ_TABLE)

    Dear everyone
    Could I ask you a question about the function module (RFC_READ_TABLE)?
    I was asked if it's possible to create a report which compares the data between different SAP systems (both production systems).
    Now, the easiest way would be to use the function module (RFC_READ_TABLE) within a SAP infoset query (SQ01 type query).
    But I heard the rumor that using the function module (RFC_READ_TABLE) is not advisable due to the security reason.
    However, I am not exactly sure what sort of security problems this function module can possibly have...
    Would you help me on this?
    I also would like to know if using "remote enabled module" type function module can always overcome this possible security issue.
    Or, are there any points that I need to be careful about even when I use "remote enabled module" function module?
    Thank you very much in advance.
    Takashi

    Dear Fred-san
    Thank you very much for your support on this.
    But, may I double check about what you mentioned above?
    So, what you were mentioning was that if some user executes the query with
    the function module (RFC_READ_TABLE), under the following conditions, he can access to
    the HR data even when he does not have the authorizations for HR transactions?
    <Conditions>
    1. the user has the authorization for HR database tables themselves
    2. RFC_READ_TABLE is called to retrieve the data from HR database
    <example>
    Data: LF_HR_TABLE like  DD02L-TABNAME value 'PA0000'.
    CALL FUNCTION 'RFC_READ_TABLE'
       EXPORTING
        query_table                = LF_HR_TABLE
      TABLES
       OPTIONS                    =
       fields                     =
       data                       =    .
    But then, as long as we call this function module for a non-critical tables such as
    VBAP (sales order) or EKKO (purchase order) within our query, it wouldn't seem to be
    so security risk to use RFC_READ_TABLE...
    Besides, each query (infoset query) has got the concept of user groups, which limits
    the access to the queries within the user group.
    ※If someone does not belong to the user group, he cannot execute the queries within that
       user group, etc
    So, my feeling is that even infoset queries does have authorization concept...
    Would you give me your thought on this?
    I also thank you for your information for SCU0.
    That is an interesting transaction
    Kind regards,
    Takashi

  • Can anyone tell me about the Training Function?

    Hi, friends
    I am a fresh man learning Siebel and I find very little information about the training function in Bookself. Can you tell me where I can find the related information?
    thanks.

    Hi,
    what kind of treinament you find? A techical/functional treinament, a user application treinament.
    If techinal treinament, the bookshelf is the better document to find information. You can use the forum, sites and Oracle Metalink to find you doubts.
    If user application treinament, where user use the application and find about how to execute a process, you can use IHelp or your company can use Oracle UPK (User Productivity Key). You can create treinament in this tool and your users can acess the treinaments.
    Regards.

Maybe you are looking for

  • Disk too slow / System overload HELP?

    I'm really hoping someone can help me out with this!: I purchased a G4 PowerBook around six months ago, with Logic Pro pre-installed. Since then, I have mixed and mastered lots of music that was recorded on a previous system and imported. I was runni

  • Relative Paths In DSN-less JDBC URL

    Whenever I've seen DSN-less URL strings for M$ Access, they've always used an absolute path to the database file: String url="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\full\\path\\src\\data\\FirstLotParts.mdb";Has anyone tried to giv

  • Sharepoint 2013 discussion board item view (flat.aspx) throws js error after being migrated from moss 2007

    After preforming a migration from moss 2007 to 2013 on-prem we have noticed that html tags are showing up in the discussion board posts.  I have tracked the problem down to the flat.aspx page throwing a js error.  'SPAnimationUtility' is undefined -

  • Home hub 5 - 5ghz & MacBook Air and MacBook Pro

    There are plenty of posts on this and none are very informative. Until a recent mac update 10.9.3 (I believe) my macs could connect to the hub as it came out of the box, however suddenly my macs stopped connecting, password error, to the hub (iPhone

  • EDIDP02 Segment in ORDERS05 Idoc

    We are in the process of testing outbound and inbound idocs of PO order create and order confirmation. While testing manually in WE19, i can sucessfully post the idocs. But, from the sap notes and the forums I have gone thru, I have observed that inb