How to Compute the average six months of customer orders excluding the first orders

Hi all
I am writing some basic sql to generate some measures from a postgres database table that are going to be inserted into a SQL SErver table.
I have to two tasks where I am supposed to generate the average 6 months spend and average 1 year spend using the customer data but excluding the first time orders.
I have some sample data below:
CREATE TABLE orders
  persistent_key_str character varying,
  ord_id character varying(50),
  ord_submitted_date date,
  item_sku_id character varying(50),
  item_extended_actual_price_amt numeric(18,2)
INSERT INTO orders VALUES ('01120736182','ORD6266073','2010-12-08','100856-01',39.90);
INSERT INTO orders   VALUES('01120736182','ORD33997609','2011-11-23','100265-01',49.99);
 INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','200020-01',29.99);
 INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','100817-01',44.99);
 INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200251-01',79.99);
 INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200269-01',59.99);
 INSERT INTO orders VALUES('01011679971','ORD89332495','2012-12-05','200102-01',169.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','100907-01',89.99);
 INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200840-01',129.99);
 INSERT INTO orders VALUES('01120736182','ORD125155068','2013-07-27','201443-01',199.99);
 INSERT INTO orders VALUES('01120736182','ORD167230815','2014-06-05','200141-01',59.99);
 INSERT INTO orders VALUES('01011679971','ORD174927624','2014-08-16','201395-01',89.99);
 INSERT into orders values('01000217334','ORD92524479','2012-12-20','200021-01',29.99);
INSERT into orders values('01000217334','ORD95698491','2013-01-08','200021-01',19.99);
INSERT into orders values('01000217334','ORD90683621','2012-12-12','200021-01',29.990);
INSERT into orders values('01000217334','ORD92524479','2012-12-20','200560-01',29.99);
INSERT into orders values('01000217334','ORD145035525','2013-12-09','200972-01',49.99);
INSERT into orders values('01000217334','ORD145035525','2013-12-09','100436-01',39.99);
INSERT into orders values('01000217334','ORD90683374','2012-12-12','200284-01',39.99);
INSERT into orders values('01000217334','ORD139437285','2013-11-07','201794-01',134.99);
INSERT into orders values('01000827006','W02238550001','2010-06-11','HL 101077',349.000);
INSERT into orders values('01000827006','W01738200001','2009-12-10','EL 100310 BLK',119.96);
INSERT into orders values('01000954259','P00444170001','2009-12-03','PC 100455 BRN',389.99);
INSERT into orders values('01002319116','W02242430001','2010-06-12','TR 100966',35.99);
INSERT into orders values('01002319116','W02242430002','2010-06-12','EL 100985',99.99);
INSERT into orders values('01002319116','P00532470001','2010-05-04','HO 100482',49.99);
Using the data, this is what I have done:
SELECT q.ord_year, avg( item_extended_actual_price_amt )  
FROM (
   SELECT EXTRACT(YEAR FROM ord_submitted_date) as ord_year,  persistent_key_str,
          min(ord_submitted_date) as first_order_date
   FROM ORDERS
   GROUP BY ord_year, persistent_key_str
) q
JOIN ORDERS o
ON q.persistent_key_str  = o.persistent_key_str and 
   q.ord_year = EXTRACT (year from o.ord_submitted_date) and 
o.ord_submitted_date > q.first_order_date AND o.ord_submitted_date < q.first_order_date + INTERVAL ' 6 months'
GROUP BY q.ord_year
ORDER BY q.ord_year
Can someone help me look into my query and see whether I am doing it the right way.
Thanks,
Ion

This more looks like a mysql code. Please try posting the question in mysql forums
http://forums.mysql.com/
This is one way of doing this in T-SQL
CREATE TABLE orders
persistent_key_str varchar(100),
ord_id varchar(50),
ord_submitted_date date,
item_sku_id varchar(50),
item_extended_actual_price_amt numeric(18,2)
INSERT INTO orders VALUES ('01120736182','ORD6266073','2010-12-08','100856-01',39.90);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','100265-01',49.99);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','200020-01',29.99);
INSERT INTO orders VALUES('01120736182','ORD33997609','2011-11-23','100817-01',44.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200251-01',79.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200269-01',59.99);
INSERT INTO orders VALUES('01011679971','ORD89332495','2012-12-05','200102-01',169.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','100907-01',89.99);
INSERT INTO orders VALUES('01120736182','ORD89267964','2012-12-05','200840-01',129.99);
INSERT INTO orders VALUES('01120736182','ORD125155068','2013-07-27','201443-01',199.99);
INSERT INTO orders VALUES('01120736182','ORD167230815','2014-06-05','200141-01',59.99);
INSERT INTO orders VALUES('01011679971','ORD174927624','2014-08-16','201395-01',89.99);
INSERT into orders values('01000217334','ORD92524479','2012-12-20','200021-01',29.99);
INSERT into orders values('01000217334','ORD95698491','2013-01-08','200021-01',19.99);
INSERT into orders values('01000217334','ORD90683621','2012-12-12','200021-01',29.990);
INSERT into orders values('01000217334','ORD92524479','2012-12-20','200560-01',29.99);
INSERT into orders values('01000217334','ORD145035525','2013-12-09','200972-01',49.99);
INSERT into orders values('01000217334','ORD145035525','2013-12-09','100436-01',39.99);
INSERT into orders values('01000217334','ORD90683374','2012-12-12','200284-01',39.99);
INSERT into orders values('01000217334','ORD139437285','2013-11-07','201794-01',134.99);
INSERT into orders values('01000827006','W02238550001','2010-06-11','HL 101077',349.000);
INSERT into orders values('01000827006','W01738200001','2009-12-10','EL 100310 BLK',119.96);
INSERT into orders values('01000954259','P00444170001','2009-12-03','PC 100455 BRN',389.99);
INSERT into orders values('01002319116','W02242430001','2010-06-12','TR 100966',35.99);
INSERT into orders values('01002319116','W02242430002','2010-06-12','EL 100985',99.99);
INSERT into orders values('01002319116','P00532470001','2010-05-04','HO 100482',49.99);
/*SELECT q.ord_year, avg( item_extended_actual_price_amt )
FROM (
SELECT EXTRACT(YEAR FROM ord_submitted_date) as ord_year, persistent_key_str,
min(ord_submitted_date) as first_order_date
FROM ORDERS
GROUP BY ord_year, persistent_key_str
) q
JOIN ORDERS o
ON q.persistent_key_str = o.persistent_key_str and
q.ord_year = EXTRACT (year from o.ord_submitted_date) and
o.ord_submitted_date > q.first_order_date AND o.ord_submitted_date < q.first_order_date + INTERVAL ' 6 months'
GROUP BY q.ord_year
ORDER BY q.ord_year
with cte as
(select *, row_number() OVER( partition by persistent_key_str order by ord_submitted_date) RN from orders )--where ord_submitted_date between dateadd(month,6,getdate()) and getdate())
SELECT year(cte.ord_submitted_date),avg(cte.item_extended_actual_price_amt) FROM cte
where rn<>1
group by year(cte.ord_submitted_date)
Satheesh
My Blog |
How to ask questions in technical forum

Similar Messages

  • My laptop computer was stolen six months ago. I had over 100 purchases from itunes on that laptop. I recently got a new laptop. Is there any way I can recover my purchases from itunes on to my new laptop?

    My laptop computer was stolen six months ago. I had over 100 purchases from itunes on that laptop. I recently got a new laptop. Is there any way I can recover my purchases from itunes on to my new laptop?

    I would ask here
    https://discussions.apple.com/community/itunes
    when you buy stuff it's connected to the appleID not the computer
    nor the appletv which have no storage so there is no option to get it from the atv

  • How to get the first day in the month from a domain date ?

    Hi,
    I like to know how to get the first day in the month from a domain date?
    Thanks
    Stephen

    Hi Gokul...
    Instead of using the funtion module you can just write the 3 statements of code to get the first day of the week.
    Its similar to the above one but instead of writing case statement you can achive the following.
    data : w_res type i,
             w_data type d,
    w_res = w_date mod 7.
    w_date = w_date - w_res.
    write w_date.
    This works.
    Regards,
    Siddarth

  • How  to  get the FIRST DAY OF THE CURRENT MONTH

    how to get the FIRST DAY OF THE CURRENT MONTH in oracle 9i.
    plzzzzz send immedaily.advance thanks

    TEST@test SQL> select trunc(sysdate,'MON') from dual;
    TRUNC(SYS
    01-OCT-06
    TEST@test SQL>                                  

  • How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    please how can one How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    What do you mean there was "no effect?" I'm not aware of any effects.
    It looks like that Service is also in the App Store. From their screen shots, the services are prefaced with WordService:
    You can see an example in the App Store for their app: App Store
    After installing, you should now have those text services in your Services menu. You can then add shortcuts in the Keyboard System Prefs.
    Most Apple apps have a Transformations menu in the Edit menu. You can Make upper, lower, and Initial caps with those. I would stick with Word Services, but you can make Application Shortcuts for the items in the Transformations menu.
    Again, in Keyboard System Prefs, Under Applications, Click the Add button on the right side pane.
    Set it for All Applications
    Enter the menu command exactly as they appear in the Transformation menu (separate entries for each),
    Make Upper Case
    Make Lower Case
    Capitalize
    Give them a shortcut.

  • Apple Mail - how to get the first word in a sentence to auto-capitalize

    How to get the first word in a sentence to auto-capitalize
    Anwar

    something to look forward to then, because we get used not to use our shift button any more, since iPhone and iPad do it for us. entourage and other ms stuff do it. pages does it too now (put it on in the auto-correct in preferences). bizarre however some loose the capitalization when you copy the text. pages to stickies or mail does not. that's good !

  • How to get the first 4 chars form a var ?

    Hi guys,
    How to get the first 4 chars form a var ?
    i.e  temp type num20 value '00000000000012345678'.
    how to move the first 4 chars to another var?
    thx in advance.

    hi
    use OFFESTS..
    example:
    var1 = '12345678'.
    var2 = var1+0(4).
    now var2 conatins '1234'.
    thx
    pavan

  • How to include the first row of detail in every xquery transformed xml?

    I am dealing with a XML file,where i need to publish to different BS.
    First node will be a common node node which contains vital info,second node goes to one BS and third goes to another BS.
    *<header></header>*
    *<details></details> (they are unbounded, but the first detail tag which comes in the input file is a mandatory tag in such a way that it needs to be included in every transformed message)*
    *<trailer></trailer>*
    We need to apply x query transformation on it in such a way:
    *</header></header>*
    *<1st detail></1st detail>*
    *<detail></detail> (2nd row of detail in input file)* -------------------------> Goes to BS1
    *<trailer></trailer>..*
    *<header></header>*
    *<1st detail></1st detail>*
    *<detail></detail> (3rd row of detail in input file)* ----------------------------->Goes to BS2
    *<trailer></trailer>*..
    And so on.
    Now, the problem is how to include the first row( *1st detail* ) of detail in every xquery transformed xml?

    are you looping of this input with a for each?
    /yourdata/details[1] should return always the first detail element.
    or before the for each do an assing of this first detail element to "generic_details_var"
    and use this var in every looping iteration (in an assign or as input for xquery)

  • How to echo the first line???

    Hi everybody,
    I need to know how to echo the first line of an XML document with a SAX parser, for example :
    <?xml version="1.0"?>I've already tried :
    public void processingInstruction(String target, String data) throws SAXException {
            System.out.println("Target = (" + target + ")");
            System.out.println("Data = (" + data + ")");
        }but it doesn't work.
    Please, help me...
    Thanks.
    Maxime.

    http://java.sun.com/webservices/docs/1.0/tutorial/doc/JAXPSAX4.html

  • How to view the first and the last frame of a clip or a selected range in the time line?

    How to view the first and the last frame of a clip directly or in a selected range in the time line ? Up arrow and down arrow keys changes only between the first frame of the consecutive clips. Even ; and ' does the same. I mean what is the shortcut keys for first to last and last to first frame of a clip? Help please.

    SELECT PurOrderNum,
    OrderDate
    FROM
    SELECT PurOrderNum,
    OrderDate,
    MAX(OrderDate) OVER (PARTITION BY DATEDIFF(mm,0,OrderDate)) AS MaxDate,
    MIN(OrderDate) OVER (PARTITION BY DATEDIFF(mm,0,OrderDate)) AS MinDate
    FROM Purchasing.PurOrder
    WHERE OrderDate >= '2013-02-28'
    AND OrderDate <= '2014-12-29'
    )t
    WHERE OrderDate = MaxDate
    OR OrderDate = MinDate
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Windows Explorer - How to select the first item once we open the explorer?

    Hi,
    In Windows Explorer - How to select the first item once we open the explorer using keyboard shortcut. I typically use downward arrow, it goes to the 2nd item in the list, then I again have to use upward arrow to go up.
    Is there a shortcut to select the first item in the list using keyboard? This is not specific to Windows 7, it has been the behavior even in previous Windows OS versions.
    Thanks,
    Mallik

    Opening a Microsoft Ticket is probably your best option. Unfortunately the change will not happen immediately and it will require multiple users to send in a ticket. I hope this ends up being resolved though.
    Good luck Mallik
    Also, don't forget to mark the post as answered so that it does not show up as unanswered to help others who search the forums.
    Agreed, MS wont change it easily. :)
    Arnav Sharma | http://arnavsharma.net/ Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading
    the thread.

  • How to select the first record?

    Hi,
    Could anyone tell me how to select the first record of every
    group?
    ex, I want to find out every customer their first purcaseDate.
    CustomerID PurcaseDate Region
    A00000001 2001/01/01 AA
    A00000001 2001/02/02 AA
    A00000002 2001/03/01 AC
    A00000002 2001/05/07 AC
    A00000003 2001/03/05 DD
    result:
    A00000001 2001/01/01 AA
    A00000002 2001/03/01 AC
    A00000003 2001/03/05 DD
    Thanks

    Vincent,
    You could do it as Carl suggested, with a couple of
    corrections.  You would need to include the CustomNo column in
    the order by clause of your cursor.  You would also need to add
    a where clause to your update statement, otherwise everywhere
    Region in the table would be updated with the same value of the
    last CustomNo in the cursor, regardless of the CustomNo in the
    table.  See corrected code below:
    DECLARE
      CURSOR     cust
      IS
      SELECT     DISTINCT CustomNo, Region, Purchase_Date
      FROM       my_table
      ORDER BY   CustomNo, Purchase_Date, Region;
      c_customer VARCHAR2 (9) := '...';
      c_region   VARCHAR2 (2) := '..';
      cntr       NUMBER := 0;
    BEGIN
      FOR x IN cust
      LOOP
        IF x.CustomNo != c_customer
        THEN
          c_customer := x.CustomNo;
          c_region := x.Region;
        ELSE
          UPDATE my_table
          SET    Region = c_region
          WHERE  CustomNo = c_customer;
          cntr := cntr + 1;
          IF cntr = 25
          THEN
            COMMIT;
            cntr := 0;
          END IF;
        END IF;
      END LOOP;
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN 
        NULL;
    END;
    Another option is that you could just use one update statement,
    like this:
    UPDATE my_table a
    SET    Region =
           (SELECT DISTINCT Region
            FROM   my_table b
            WHERE  (CustomNo, Purchase_Date) IN
                   (SELECT   CustomNo, MIN (Purchase_Date)
                    FROM     my_table
                    GROUP BY CustomNo)
            AND    a.CustomNo = b.CustomNo)
    Barbara

  • How far dose the first generation's iPad iOS  updates go?

    I cannot download  some of the new apps because my iPad has to have the latest iOS.
    When I go to download the latest iOS it states that I have the latest version.
    So , my question is : How far dose the first generation's iPad iOS  updates go?
    How can I upgrade to the very latest iOS?
    I also get knocked off from websites a lot.
    Thanks in Advance.

    5.1.1.
    (103242)

  • How to fix the first field or column in classical report while scrolling

    i want to know, how to fix the first field or column in classical report while scrolling
    horizontally. the first  should be constant when i scroll the report horizontally .
    please help me.
    it's urgent.

    Hi,
    Suppose your first field is itab-matnr.
    WRITE :/ itab-matnr.
    SET LEFT SCROLL-BOUNDARY.
    WRITE :/......."Remianing fields

  • How to compute the italian codice fiscale

    Is there anyone who can give me a PL/SQL or a package computing the italian codice fiscale getting in input Name, Sirname, birthdate, ...?
    I suppose it exists and I don't want to reinvent the wheel.
    My oracle version is 8.1.7 i
    Thanks in advance!

    Maybe
    using http://www.paginainizio.com/service/strutturacodicefiscale.htm but NOT TESTED (just something to play with)
    declare
    /* input data */
      nome    varchar2(50) := 'SUONOME';                       /* first name */
      cognome varchar2(50) := 'COGNOME';                       /* last name */
      nascita date         := to_date('19331122','yyyymmdd');  /* date of birth */
      sesso   varchar2(1)  := 'M';                             /* gender */
      comune  varchar2(4)  := 'A123';                          /* birthplace code */
    /* obtaining first/last name vowels and consonants */
      nome_c  varchar2(50) := translate(upper(nome),'~AEIOU','~');          /* first name consonants - vowels deleted */
      nome_v  varchar2(50) := translate(upper(nome),'~'||nome_c,'~');       /* first name vowels - consonants deleted */
      cnome_c varchar2(50) := translate(upper(cognome),'~AEIOU','~');       /* last name consonants - vowels deleted */
      cnome_v varchar2(50) := translate(upper(cognome),'~'||cnome_c,'~');   /* last name vowels - consonants deleted */
    /* computing code components */
      campo_1 varchar2(3)  := substr(substr(nome_c,1,1)||substr(nome_c,3,1)||substr(nome_c,4,1)||nome_v,1,3);         /* 1st,3rd,4th first name consonant */
      campo_2 varchar2(3)  := substr(substr(cnome_c,1,1)||substr(cnome_c,2,1)||substr(cnome_c,3,1)||cnome_v,1,3);     /* 1st,2nd,3rd last name consonant */
    /* vowels should be concatenated when there are not enough consonants -> how about DARIO FO ? DAI FO? */
      campo_3 varchar2(2)  := to_char(nascita,'YY');                                                                  /* last two digits of year of birth */
      campo_4 varchar2(1)  := substr('ABCDEHLMPRST',to_number(to_char(nascita,'MM')),1);                              /* month of birth converted */
      campo_5 varchar2(2)  := lpad(to_char(to_number(to_char(nascita,'DD')) + decode(sesso,'M',0,'F',40,100)),2,'0'); /* day of birth + 40 for women */
      campo_6 varchar2(4)  := comune;
    /* concatenating code (without check character) */
      codice  varchar2(16) := campo_1 || campo_2 || campo_3 || campo_4 || campo_5 || campo_6;
    /* conversion tables for check character computation */
      caratt  varchar2(36) := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';                                      /* characters to be converted */
      p_pari  varchar2(72) := '000102030405060708090001020304050607080910111213141516171819202122232425';  /* corresponding conversion numbers for even positions */
      p_disp  varchar2(72) := '010005070913151719210100050709131517192102041820110306081214161022252423';  /* corresponding conversion numbers for odd positions */
    /* auxiliary fields */
      somma   pls_integer  := 0;
      posiz   pls_integer;
    begin
      for i in 1 .. 15
      loop
        posiz := instr(caratt,substr(codice,i,1)));  /* the position of the i-th code character in the conversion table */
        if mod(i,2) = 0 then
          somma := somma + to_number(substr(p_pari,2 * posiz - 1,2));  /* the corresponding number added to the sum for even code character positions */
        else
          somma := somma + to_number(substr(p_disp,2 * posiz - 1,2));  /* the corresponding number added to the sum for odd code character positions */
        end if;
      end loop;
      somma := mod(somma,26);  /* the remainder of division */
      codice := codice || substr(caratt,somma + 11,1);  /* concatenating the check character */
      dbms_output.put_line(codice);
    end;Regards
    Etbin
    Edited by: Etbin on 24.12.2011 7:38
    row changed to if mod(i,2) = 0 then

Maybe you are looking for

  • Skin for macbook pro early 2008

    hi everybody quick question. i would like to buy a hard case shell or skins for my macbook pro early 2008. but i cannot find anything like this anymore on the internet. does somebody know a company (best here in the UK) who sales them?? thank you for

  • How do i know if i made a purchase and if I did accidentally, how can I reverse it?

    How do i know if i made a purchase and if I did accidentally, how can I reverse it?

  • SQL query - using regexp_like?

    I have a table with 35m rows. eg: create table table1 as (   unique_id  number,   some_data varchar2(10),   test_column varchar2(10) insert into table1 values (1, 'test1','abc'); insert into table1 values (2, 'test2','abcd'); insert into table1 value

  • Help! Sophos popup leads to generally useless computer...

    Hi all! I have a pretty strange situation going on on my parents' computer. My mom claims that she didn't install Sophos (an anti-virus program) on her iMac, yet when she logged onto the computer today, a window saying "Threat detected by Sohpos Anti

  • Sound Blaster Live! 24-

    This is my first sound card. (Don't laugh) I am pretty PC knowlegable, but I'm not sure whats going on with this thing. Let me give you my specs first: AMD Athlon 600+ (.4 Ghz) Windows XP (Home) SP2 024 DDR (PC2700) RAM BFG 6200 (OC) 256 MB AGP So my