Analytic function to retrieve a value one year ago

Hello,
I'm trying to find an analytic function to get a value on another row by looking on a date with Oracle 11gR2.
I have a table with a date_id (truncated date), a flag and a measure. For each date, I have at least one row (sometimes 2), so it is gapless.
I would like to find analytic functions to show for each date :
sum of the measure for that date
sum of the measure one week ago
sum of the measure one year ago
As it is gapless I managed to do it the week doing a group by date in a subquery and using a LAG with offset set to 7 on top of it (see below).
However I'm struggling on how to do that for the data one year ago as we might have leap years. I cannot simply set the offset to 365.
Is it possible to do it with a RANGE BETWEEN window clause? I can't manage to have it working with dates.
Week :LAG with offset 7
SQL Fiddle
or
create table daily_counts
  date_id date,
  internal_flag number,
  measure1 number
insert into daily_counts values ('01-Jan-2013', 0, 8014);
insert into daily_counts values ('01-Jan-2013', 1, 2);
insert into daily_counts values ('02-Jan-2013', 0, 1300);
insert into daily_counts values ('02-Jan-2013', 1, 37);
insert into daily_counts values ('03-Jan-2013', 0, 19);
insert into daily_counts values ('03-Jan-2013', 1, 14);
insert into daily_counts values ('04-Jan-2013', 0, 3);
insert into daily_counts values ('05-Jan-2013', 0, 0);
insert into daily_counts values ('05-Jan-2013', 1, 1);
insert into daily_counts values ('06-Jan-2013', 0, 0);
insert into daily_counts values ('07-Jan-2013', 1, 3);
insert into daily_counts values ('08-Jan-2013', 0, 33);
insert into daily_counts values ('08-Jan-2013', 1, 9);
commit;
select
    date_id,
    total1,
    LAG(total1, 7) OVER(ORDER BY date_id) total_one_week_ago
  from
      select
        date_id,
        SUM(measure1) total1
      from daily_counts
      group by date_id
order by 1;
Year : no idea?
I can't give a gapless example, would be too long but if there is a solution with the date directly :
SQL Fiddle
or add this to the schema above :
insert into daily_counts values ('07-Jan-2012', 0, 11);
insert into daily_counts values ('07-Jan-2012', 1, 1);
insert into daily_counts values ('08-Jan-2012', 1, 4);
Thank you for your help.
Floyd

Hi,
Sorry, I;m not sure I understand the problem.
If you are certain that there is at least 1 row for every day, then you can be sure that the GROUP BY will produce exactly 1 row per day, and you can use LAG (total1, 365) just like you already use LAG (total1, 7).
Are you concerned about leap years?  That is, when the day is March 1, 2016, do you want the total_one_year_ago column to reflect March 1, 2015, which was 366 days earlier?  If that case, use
date_id - ADD_MONTHS (date_id, -12)
instead of  365.
LAG only works with an exact number, but you can use RANGE BETWEEN with other analytic functions, such as MIN or SUM:
SELECT DISTINCT
          date_id
,         SUM (measure1) OVER (PARTITION BY date_id)    AS total1
,         SUM (measure1) OVER ( ORDER BY      date_id
                                RANGE BETWEEN 7 PRECEDING
                                      AND     7 PRECEDING
                              )                       AS total1_one_week_ago
,         SUM (measure1) OVER ( ORDER BY      date_id
                                RANGE BETWEEN 365 PRECEDING
                                      AND     365 PRECEDING
                              )                       AS total1_one_year_ago
FROM      daily_counts
ORDER BY  date_id
Again, use date arithmetic instead of the hard-coded 365, if that's an issue.
As Hoek said, it really helps to post the exact results you want from the given sample data.  You're miles ahead of the people who don't even post the sample data, though.
You're right not to post hundreds of INSERT statements to get a year's data.  Here's one way to generate sample data for lots of rows at the same time:
-- Put a 0 into the table for every day in 2012
INSERT INTO daily_counts (date_id, measure1)
SELECT  DATE '2011-12-31' + LEVEL
,       0
FROM    dual
CONNECT BY LEVEL <= 366

Similar Messages

  • Function to find the Last Date of Month One Year Ago - RETURNS ERROR

    I've written sql code which takes a date and finds the Last Day of the Month one year ago. For example,  it takes the date '2015-04-17' and returns the date '2014-04-30'. The code works fine in a query. Now I'm trying to turn this into a function. However,
    when I try to create the function I get the error:
    Operand type clash: date is incompatible with int
    Why is this error being returned?
    Here is my function:
    CREATE FUNCTION dbo.zEOM_LY_D(@Input Date)
           RETURNS date
    AS
    BEGIN;
      DECLARE @Result date;
      SET @Result =  convert(DATE, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,dateadd(m, -11, @Input)+1),0)),101)
        RETURN @Result;
    END;
    Thanks for any help you can give.
                     

    Stan,
    Thanks very much- that does the trick. I should have said I am using SQL 2008 so EOMONTH is not available to me. I still don't get why I got an error though, since I was treating a date like a date and not like an int.
    Thanks, John
    I think i found the issue but i do not know why it is causing the issue. i think may be the way dates are treated/stored internally..i think dates are stored as no of days after 0001/01/01 but cannot see how this cwould effect..may be somebody else can through
    some light..... 
    if you make it as datetime it will work,
    if you leave it as date - eliminate adding 1...  you should prefer to use dateadd to add/substract dates.
    try this to understand..
    --removed the +1 in the code
    declare @input date
    set @input ='20150503'
    select
    convert(DATE, DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,dateadd(m, -11, @Input)),0)),101)
    go
    --made the datatype as datetime
    declare @input datetime
    set @input ='20150503'
    select
    convert(DATE, DATEADD(s,-1,DATEADD(mm,DATEDIFF(m,0,dateadd(m, -11, @Input)+1),0)),101)
    Hope it Helps!!

  • Function module to get 'Date one year in the past' in APO

    Hi,
    Required function module to get date one year in the past in APO.
    Thanks and regards,
    M.R.Reddy.

    Hi Reddy,
    Try these function modules
    /SAPAPO/DATE
    /SAPAPO/FISCAL_BDATE
    /SAPPO/MAPI_MAP_CREATDATE
    /SAPPO/MAPI_MAP_POSTDATE
    /SAPAPO/LCP_CALC_DATE
    /SAPAPO/VS_ORDER_GET_DATES
    /SAPAPO/PERIOD_CONVERT_DATE
    /SAPAPO/PERIOD_DATE_GET_FROMTO
    /SAPAPO/PERIOD_GET_DATE_RANGE
    /SAPAPO/PERIOD_GET_FOR_DATE
    /SAPAPO/PERIOD_GET_FROM_TODATE
    Regards
    R. Senthil Mareeswaran.

  • Required function module to get date one year in the past.

    Hi,
    Required function module to get date one year in the past.
    Thanks and regards,
    M.R.Reddy.

    Hello,
    You can check this:
    DATA:
    V_DATE1 TYPE D,
    V_DATE2 TYPE D.
    V_DATE1 = SY-DATUM.
    TRY.
        CALL METHOD CL_HRPAD_DATE_COMPUTATIONS=>SUBTRACT_YEARS_FROM_DATE
          EXPORTING
            START_DATE = V_DATE1
            YEARS      = 1
          RECEIVING
            DATE       = V_DATE2.
      CATCH CX_HRPA_VIOLATED_POSTCONDITION .
    ENDTRY.
    WRITE:
    / V_DATE1, / V_DATE2.
    Hope this helps.
    Br,
    Suhas

  • Can I view history from one year ago?

    I'm trying to find out what sites I was on one year ago but the history only keeps track up to 6 months. Is there any way to retrieve history from a year ago?

    No, if history is only kept for 6 ,months then older history is no longer available.<br />
    The default in Firefox 3 versions is to keep history for 180 days (6 months).<br />
    * http://kb.mozillazine.org/browser.history_expire_days
    In Firefox 4+ that has changed to a maximum number of pages that is kept.<br />
    So you can update to Firefox 8 and it will remember more history, but you can't get back older history.<br />
    <br />
    There is no time limit in Firefox 4+ versions for the history.<br />
    Firefox determines automatically how many pages can be kept without affecting the performance.<br />
    You can see the current value via the reads-only pref places.history.expiration.transient_max_pages on the about:config page.
    See:
    * http://blog.bonardo.net/2010/01/20/places-got-async-expiration

  • I buy adobe creative suite for teachers and students about one year ago but now i'm not longer a student. Can I still use this programs legally for commercial purposes or do I have to buy some upgrades or something like this? Please help

    I buy adobe creative suite for teachers and students about one year ago but now i'm not longer a student. Can I still use this programs legally for commercial purposes or do I have to buy some upgrades or something like this? Please help

    The license did not have use restrictions Licenses and terms of use | Adobe
    BUT... when your one year Education account ends, I do not think you will be able to renew at the Education rate

  • I have an IPad mini and I changed the Apple ID and the password almost one year ago and, for a while, a message asking me to sign in to iCloud pops- up constantly. My iCloud account is registered with an old email and password. I do not remember the

    I have an IPad mini and I changed the Apple ID and the password almost one year ago and, for a while, a message asking me to sign in to ICloud pops- up constantly. My ICloud account is registered with an old email address and password. I do not remember the password to my ICloud account, and ID address that my ICloud account is registered under is an old email adress which is deleted right now (the old mail account is deleted). I don’t have a rescue email adress and I don’t know the answers to the security questions, so I have no way of changing the ICloud password. A message asking me to sign in to ICloud pops up constantly, but I always just hit cancel. However, now I am unable to access Find My IPad. How do I get my ICloud account changed and registered to be under my current Apple ID (email) and password? It is possible to set the device as New Ipad?

    Welcome to the Apple community.
    If you are unable to remember your password, security questions, don’t have access to your rescue address or are unable to reset your password for whatever reason, your only option is to contact Apple ID Support, upon speaking to an operator you should explain that your problem is related to your Apple ID, this way you will not be charged for assistance, even if you don’t have an AppleCare plan.
    The operator will take you through some steps you may have already tried, however they need to be sure they have exhausted all usual approaches before trying to reset your account, so you should try to be helpful and show patience with the procedure.
    The operator will need to verify they are speaking to the account holder and may ask you some questions that only the account holder could know, and you will need to answer them if the process is to proceed.
    Once the operator has verified your identity they will send a message through to your device which contains an alpha numeric code, which you will need to read back to them.
    Once this has been completed they will send an email to your iCloud email address after a period of 24 hours, so you should check that mail is enabled in your devices iCloud settings.
    Upon receipt of the email, use the reset link provided to reset your password, after which you should be able to make the adjustments to iCloud that you wish to do.

  • To whom it may concern      Hi my name is Silvana Pires,I purchased an I Phone 4 S Model A 1387 EMC 2430 SCC.ID DCG E  2430 AIC.579 C-E 243 A in California one year ago,Unfortunately its Not working well the screen is getting black,and the phone is in goo

    To whom it may concern
    Hi my name is Silvana Pires,I purchased an I Phone 4 S Model A 1387 EMC 2430 SCC.ID DCG E
    2430 AIC.579 C-E 243 A in California one year ago,Unfortunately its Not working well the screen is getting black,and the phone is in good shape I can prove it,the Apple support in Brazil doenst work like in USA.
    I look forward to your reply and a resolution of this problem.
    Thank you very much!!!

    You are welcome. I'm glad you got it back up.
    (1) You say you did the symbolic link. I will assume this is set correctly; it's very important that it is.
    (2) I don't know what you mean by "Been feeding the [email protected] for several weeks now, 700 emails each day at least." After the initial training period, SpamAssassin doesn't learn from mail it has already processed correctly. At this point, you only need to teach SpamAssassin when it is wrong. [email protected] should only be getting spam that is being passed as clean. Likewise, [email protected] should only be getting legitimate mail that is being flagged as junk. You are redirecting mail to both [email protected] and [email protected] ... right? SpamAssassin needs both.
    (3) Next, as I said before, you need to implement those "Frontline spam defense for Mac OS X Server." Once you have that done and issue "postfix reload" you can look at your SMTP log in Server Admin and watch as Postfix blocks one piece of junk mail after another. It's kind of cool.
    (4) Add some SARE rules:
    Visit http://www.rulesemporium.com/rules.htm and download the following rules:
    70sareadult.cf
    70saregenlsubj0.cf
    70sareheader0.cf
    70sarehtml0.cf
    70sareobfu0.cf
    70sareoem.cf
    70sarespoof.cf
    70sarestocks.cf
    70sareunsub.cf
    72sare_redirectpost
    Visit http://www.rulesemporium.com/other-rules.htm and download the following rules:
    backhair.cf
    bogus-virus-warnings.cf
    chickenpox.cf
    weeds.cf
    Copy these rules to /etc/mail/spamassassin/
    Then stop and restart mail services.
    There are other things you can do, and you'll find differing opinions about such things. In general, I think implementing the "Frontline spam defense for Mac OS X Server" and adding the SARE rules will help a lot. Good luck!

  • Hi, I have a MAC (version 10.10.2) and installed Creative Suite one year ago. Now I want to open the Illustrator, but it does not work. It says I should install old Java SE 6-Runtime-Version to open „Adobe Illustrator CS6". Where can I find it? Thanks for

    Hi, I have a MAC (version 10.10.2) and installed Creative Suite one year ago. Now I want to open the Illustrator, but it does not work. It says I should install old Java SE 6-Runtime-Version to open „Adobe Illustrator CS6“. Where can I find it? Thanks for your answer! Jana

    Prompted to install Java SE 6 Runtime | Mac OS 10.9
    Mylenium

  • First day of current month, one year ago

    All,
    Does anyone have a calculation or know how I can calculate the first day of the current month, one year ago? I am trying to setup a filter criteria to show all records created >= 1st day of current month for prior year and <= the last day of the prior month. I have the second half of the equation for last day prior month but need some help on the first half.
    Thanks in advance for any pointers!
    D

    You can try:
    SELECT TRUNC(ADD_MONTHS(sysdate, -12), 'MON') FROM dual;
    Or
    SELECT TRUNC(sysdate-NUMTOYMINTERVAL(1,'YEAR'), 'MON') FROM dual;

  • Since purchasing my iPhone 5 one year ago, I'm unable to leave reviews for any app

    I purchased my iPhone 5 one year ago. Since then I can't leave a review for any app. I contacted iTunes &amp; they said it was the particular app. However, it's every single app. I can't leave a review for any at all. What's up? Is there something that's turned off in my settings?

    I deleted the app multiple times, and restarted my phone, I even did a complete restore...nothing worked, UNTIL I changed my password once again...I had changed my password 3 times in an attempt to get it to work, and not until I changed it for the fourth time last night did the app finally accept my new credentials
    It was such a goofy bug, but I'm glad to be rid of it...thanks all!

  • HT201238 My account was not automatically upgraded to an new annual plan, I got it one year ago and I got a message saying my Icloud storage was full and I that I only had 5gb free. What can I do ?

    My account was not automatically upgraded to an new annual plan, I got it one year ago and I got a message saying my Icloud storage was full and I that I only had 5gb free. What can I do ?

    Thanks Winston, thats the first thing I wanted to do but I dont see any Annual Plan (like I had), only monthly plans, and they said that as I got a Storage Plan before September 2014 I would be "automatically" updgraded to a new annual plan with reduced pricing. Dont know how I can get it now.

  • Hello, I installed LR5 on my Desktop PC (MAC) one year ago by upgrading from LR4 using a Download from the adobe store. Now I want to install LR5 on my laptop. Fir?st I used the LR4-Installation-CD. What´s next

    Hello, I installed LR5 on my Desktop PC (MAC) one year ago by upgrading from LR4 using a Download from the adobe store. Now I want to install LR5 on my laptop. First I used the LR4-Installation-CD. What´s next? How can I upgrade to LR5?

    Installing CleanMyMac was just about the worst thing you could do. Get rid of it: Re: cleanmymac2

  • HT1212 I found an iphone over one year ago. Its locked with a passcode. I kept waiting for the owner to call it. They never did. I went to ATT store today, they put a new sim card in it. but now itunes needs the passcode to reset it to factory settings.

    I found an iphone over one year ago. Its locked with a passcode. I kept waiting for the owner to call it. They never did. I went to an AT&T store today, they put a new sim card in it. and told me to go home, log on to itunes, and restore the phone to "factory settings".But itunes says the phone is locked and it needs the passcode to reset it to factory settings.
    Any workaround? Or, am I doing something wrong here?
    Thanks so much.
    Joe

    Sounds like you may be the owner of a new phone!  If you don't need or want it and no one claims it you probably can sell it. Check eBay to see what the going rate is.
    You are to be commended for at least trying to find the owner. Many wouldn't. 
    Best.
    GDG

  • HT4061 Device had been purchased in Hong Kong less than one year ago. May I get warranty service in London?

    Device had been purchased in Hong Kong less than one year ago. May I get warranty service in London? Actually i have problem of "Error 23" and didn't succeed to solve it.

    Warranty and support for the iPhone are provided only in the country in which the iPhone was officially sold. To get service for an iPhone purchased in Hong Kong, you'll have to take the iPhone back to HK or send it to someone you know there who can get it serviced and then ship it back to you.
    Regards.

Maybe you are looking for

  • Can parents read text messages online!?!

    if parents read txt mssgs online can I delete them before they can see them!? if so how I need to know!!!!!!!!!!!!!!!!! -Emma

  • Anyone succesfully configured a LinkSys WRT54G using a G5 tower for the IPh

    Hi, Anyone succesfully configured a LinkSys WRT54G using a G5 tower for the IPhone? If so please, could you give megive me the router configurations? As my wi-fi network won't even showup on IPhone. Thanx SvK

  • Two problems with PSE8 (trial version)

    I have two problems I'm experiencing in PSE8. I'm working in Windows PSE8. 1. I keep going to the drop down menu under "Edit" to the Preset Manager--Brushes. I would like Large Thumbnails. I tell it "OK" but it never changes anything. Am I doing some

  • Enable substitution in MSS

    Hi folks, I have copied MSSBIZVIEW and MSSVIEW_SUB to the customer namespace and now I am wondering how to enable substitution in the MSS role on portal? please help. Thanks & Regards Sahil Kohli

  • TRANSCEND JET FLASH 350 USB 2.O FLASH DRIVE NOT DETECTED

    I AM HAVING DESK TOP PC P2 1401IL   WITH WINDOWS 7 TOTAL 4 USB DRIVES ARE THERE. TWO FRONT  TWO BACK I PURCHASED A TRANSCEND JET FLASH 350 USB 2 FLASH DRIVE,WHEN THE DRIVE IS ATTACHED TO THE PORT THE SYSTEM IS NOT DETECTING THE DRIVE.I TESTED THE SAM