Getting the data for last month of every year

Hi,
       How to declare the date if we want to pull the data from the December of every year.
For example if the query is run in march 2015 and they want the historical data it should pull only the data from dec 2014.
In the same way if they ran the query in future jun 2016 and if they want to historical data it should pull only data from dec 2015.
It should not coded manually. Please help me with date format that need to used.
BALUSUSRIHARSHA

Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
A table has to have a key to be table.  Here is my guess at a repair job: 
CREATE TABLE Test_Data
(pu_id INTEGER NOT NULL
  REFERENCES PU(pu_id),
 pu_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL,
 PRIMARY KEY (pu_id, pu_date),
 x_count INTEGER,
 y_count INTEGER);
Identifiers are not numeric in a good schema. What math do you do with them? They are also the key in the table that models the entity they identify. Where is the PU table (and what is a PU anyway)? 
INSERT INTO Test_Data
VALUES
(28, '2014-01-01', 10, 20), -- crap! No key in this mess!! 
(28, '2015-01-01', 30, 20), -- 
(28, '2014-12-12', 10, 20), 
(28, '2015-02-02', 10, 20);
A PIVOT is not a query and not even part of SQL. It is how Microsoft programmers who do not know RDBMS or have a report writer violate the tiered architecture of SQL. We also do not use XML mixed in SQL. It is a bitch to maintain, has poor performance and again
violates the tiered architecture principle. 
A query is not sorted because it is a table. A file in COBOL can be sorted and that seems to be what you really want to write. 
Old COBOL love the Sybase CONVERT() string function to avoid SQL temporal data. 
We never use SELECT * in production code; Google it. Not only are you generating code, you are generation bad code. 
Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
The report period table gives a name to a range of dates that is common to the entire enterprise. 
CREATE TABLE Month_Periods
(month_name CHAR(10) NOT NULL PRIMARY KEY
   CHECK (month_name LIKE <pattern>),
 month_start_date DATE NOT NULL,
 month_end_date DATE NOT NULL,
  CONSTRAINT date_ordering
    CHECK (month_start_date <= month_end_date),
etc);
These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
This will port and waste time calling string function row by row. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • How to get the data for last 3rd business day and also include saturday and sunday if its a wednesday?

    Hi All,
    I have a simple query which is below:-
    Declare @reportdate date
    set @reportdate= (DATEADD(dd,-5,getdate()))
    select * from dbo.Table
    where date IN (@reportdate)
    I need this query to pull the data for the last 3rd business day .So lets say today is monday then i need the data for last week wednesday which is 3 business days back from monday, if today is a tuesday it would be for last thursday ( as 3 business days for
    tuesday would be thursday). But if today is wednesday then i need to be last 3rd business day which is last friday and i also need to get the data for saturday and sunday.
    Can someone please help me how cani change my filter to do this?
    Please let me know if i am still unclear.
    Thanks

    Hi SqlDev12,
    Based on my understanding on your requirement, you can reference the below sample.
    CREATE TABLE BusinessTable
    Bdate DATE,
    Wd VARCHAR(10)
    ;WITH Cte(DT,WD) AS
    SELECT CAST('20150401' AS DATE),DATENAME(WEEKDAY,CAST('20150401' AS DATE))
    UNION ALL
    SELECT DATEADD(DAY,1,DT),DATENAME(WEEKDAY,DATEADD(DAY,1,DT)) FROM Cte
    WHERE DT<GETDATE()
    INSERT INTO BusinessTable SELECT * FROM Cte
    SELECT * FROM BusinessTable
    SET DATEFIRST 7 -- Set Sunday as the first day of a week
    DECLARE @givenDay DATE ='20150415' --Wednesday
    SELECT * FROM BusinessTable
    WHERE Bdate BETWEEN
    --For Monday and Sunday, select last wednesday
    (CASE WHEN DATEPART(WEEKDAY,@givenDay) IN(1,2) THEN DATEADD(DAY,2,DATEADD(WEEK,DATEDIFF(WEEK,0,@givenDay)-1,0))
    --For Tuesday and Wednesday, last week's Thursday and Friday
    WHEN DATEPART(WEEKDAY,@givenDay) IN(3,4) THEN DATEADD(DAY,-5,@givenDay)
    --For Thursday and Friday, current week's Monday and Tuesday
    WHEN DATEPART(WEEKDAY,@givenDay) IN(5,6) THEN DATEADD(DAY,-3,@givenDay)
    --For Saturday, current week's Wednesday
    ELSE DATEADD(DAY,2,DATEADD(WEEK,DATEDIFF(WEEK,0,@givenDay),0)) END)
    AND
    (CASE WHEN DATEPART(WEEKDAY,@givenDay) IN(1,2) THEN DATEADD(DAY,2,DATEADD(WEEK,DATEDIFF(WEEK,0,@givenDay)-1,0))
    WHEN DATEPART(WEEKDAY,@givenDay) IN(3) THEN DATEADD(DAY,-5,@givenDay)
    WHEN DATEPART(WEEKDAY,@givenDay) IN(4) THEN DATEADD(DAY,-3,@givenDay)
    WHEN DATEPART(WEEKDAY,@givenDay) IN(5,6) THEN DATEADD(DAY,-3,@givenDay)
    ELSE DATEADD(DAY,2,DATEADD(WEEK,DATEDIFF(WEEK,0,@givenDay),0)) END)
    DROP TABLE BusinessTable
    If you have any feedback on our support, you can click
    here.
    Eric Zhang
    TechNet Community Support

  • How to get the date for the first monday of each month

    Dear Members,
    How to get the date for the first monday of each month.
    I have written the following code
    SELECT decode (to_char(trunc(sysdate+30 ,'MM'),'DAY'),'MONDAY ',trunc(sysdate+30 ,'MM'),NEXT_DAY(trunc(sysdate+30 ,'MM'), 'MON')) FROM DUAL
    But it look bith complex.
    Abhishek
    Edited by: 9999999 on Mar 8, 2013 4:30 AM

    Use IW format - it will make solution NLS independent. And all you need is truncate 7<sup>th</sup> day of each month using IW:
    select  sysdate current_date,
            trunc(trunc(sysdate,'mm') + 6,'iw') first_monday_the_month
      from  dual
    CURRENT_D FIRST_MON
    08-MAR-13 04-MAR-13
    SQL> Below is list of first monday of the month for this year:
    with t as(
              select  add_months(date '2013-1-1',level-1) dt
                from  dual
                connect by level <= 12
    select  dt first_of_the_month,
            trunc(dt + 6,'iw') first_monday_the_month
      from  t
    FIRST_OF_ FIRST_MON
    01-JAN-13 07-JAN-13
    01-FEB-13 04-FEB-13
    01-MAR-13 04-MAR-13
    01-APR-13 01-APR-13
    01-MAY-13 06-MAY-13
    01-JUN-13 03-JUN-13
    01-JUL-13 01-JUL-13
    01-AUG-13 05-AUG-13
    01-SEP-13 02-SEP-13
    01-OCT-13 07-OCT-13
    01-NOV-13 04-NOV-13
    FIRST_OF_ FIRST_MON
    01-DEC-13 02-DEC-13
    12 rows selected.
    SQL> SY.

  • How to get the date for the last day of a week?

    Is there a easy way to get the date for the last day of week?
    eg a week starts on monday and end on sunday
    January 11, 2005 is the start date for the week
    January 17, 2005 is the end date for the week
    or
    say
    February 26, 2003 is the start date for the week
    March 5, 2003 is the end date for the week
    I just need a simple way of figuring that out....
    I figured out how to get the start date for the week but just can't get the latter..
    formatting of the date is not of a concern.. that I know how to do
    thanks in advance

    How about something like the following?
         Calendar someDay = new GregorianCalendar(2005,0,11);//2005 Jan, 11
         //Note above that January is 0, not 1, as counting starts from 0.
          someDay.add(Calendar.DAY_OF_MONTH,6); //add 6 days
         java.util.Date  lastDayOfWeek = someDay.getTime();
         //If someDay was the start of a week, lastDayOfWeek should now be
         //the last day of that week.
         System.out.println(lastDayOfWeek.toString() );

  • Where can we get the data for pre calculated reports

    Hi,
    i want to see the data for pre calculated reports (Reporting agent)
    where can we get the data for pre calculated reports
    Thanks & Regards,
    Shaliny. M

    Dear,
    This feature of precalculating reports is to enhance the report performance. You will need to schedule this periodically, so that the report is fetched and cached. This allows faster retrieval of report data. Plz. understand that, this scheduling needs to run after every data load in the corresponding cube, so that, the latest data is cached, else the report data will be obsolete.
    Thanks

  • How would I get the date of last Monday?

    How would I get the date of last Monday?

    I've done the following, does it seem right?
    public static const millisecondsPerDay:int = 1000 * 60 * 60 *
    24;
    * This function sets the mimimum and maximum range
    private function sliceChartWeek():void{
    var max:Date = new Date();//current date is our max from
    which we will calculate the min
    var day:uint = max.day;
    var min:Date = new Date(max.getTime() - (millisecondsPerDay
    * (max.day - 1)));
    dateTimeAxis.minimum = min;
    }

  • Generate all the dates for given month

    Hi all,
    How can I generate all the dates for given month? For example If I give Feb-2008 then it should display all the dates from 01/02/2008 to 29/02/2007
    Thanks,
    Sujnan

    This question was expanded (and answered) at
    Monthly Report
    You can also search for "all days in month".

  • Function module to get the next new 12 months of a year

    Hi All,
    I have a requirement to get the next new 12 months of a year from the current month , i.e. if my current month is June 2009 , I need to get June 2009, July 2009,...................., May 2010 .
    Does anybody know if there is any function module for this or is there any logic to implement this .
    Please could someone help me out with this.
    Regards,
    Sushanth H.S.

    Dear Srinivas,
    Have a look at the below code. It works fine. Change according to your req.
    REPORT ztest_notepad.
    DATA:
          month_index TYPE i,
          wa_t015m    TYPE t015m,
          it_t015m    TYPE t015m OCCURS 0 WITH HEADER LINE.
    DATA:
          BEGIN OF it_next12 OCCURS 0,
            months_12 TYPE string,
          END OF it_next12.
    PARAMETERS:
          p_month TYPE num2,
          p_year  TYPE num4.
    START-OF-SELECTION.
      SELECT * FROM t015m INTO TABLE it_t015m WHERE spras = sy-langu.
      READ TABLE it_t015m INTO wa_t015m WITH KEY monum = p_month.
      IF sy-subrc = 0.
        month_index = sy-tabix.
        LOOP AT it_t015m INTO wa_t015m FROM month_index TO 12.
          CONCATENATE wa_t015m-monam p_year INTO it_next12-months_12 SEPARATED BY '-'.
          APPEND it_next12.
          CLEAR  it_next12.
        ENDLOOP.
        p_year = p_year + 1.
        LOOP AT it_t015m INTO wa_t015m FROM 1 TO month_index.
          CONCATENATE wa_t015m-monam p_year INTO it_next12-months_12 SEPARATED BY '-'.
          APPEND it_next12.
          CLEAR  it_next12.
        ENDLOOP.
      ENDIF.
      LOOP AT it_next12.
        WRITE:/ it_next12-months_12.
      ENDLOOP.
    Thanks
    Venkat

  • How to get same day of a month in every year in the DB ( To update a flag )

    Hi,
    I am trying to formulate an update query for a flag table in our database which contains dates, and flag columns. Currently the system have dates for the next ten years. The flags are updated with values 0 or 1 if a particular date falls under the required criteria.
    I need to update flag column for the same day of the month in every year. e.g. 2nd Sunday of October. The value should be updated to all years in the table. Currently I am using the following query to update the current year.
    UPDATE FILTERCALENDAR SET YEAR_WINDOW=1 WHERE c_date = NEXT_DAY( TO_DATE('OCT-2013','MON-YYYY'), 'SUNDAY') + (2-1)*7;
    and for next year Like
    UPDATE FILTERCALENDAR SET YEAR_WINDOW=1 WHERE c_date = add_months(NEXT_DAY( TO_DATE('OCT-2013','MON-YYYY'), 'SUNDAY') + (2-1)*7,+12)-1;
    This is not an excellent way to do it as it does not take care of leap years and it does not scan and update values in the whole table for all years correctly.
    Can any one help me to resolve this please.

    Hi,
    user10903866 wrote:
    Hi,
    I am trying to formulate an update query for a flag table in our database which contains dates, and flag columns. Currently the system have dates for the next ten years. The flags are updated with values 0 or 1 if a particular date falls under the required criteria.
    I need to update flag column for the same day of the month in every year. e.g. 2nd Sunday of October. The value should be updated to all years in the table. Currently I am using the following query to update the current year.
    UPDATE FILTERCALENDAR SET YEAR_WINDOW=1 WHERE c_date = NEXT_DAY( TO_DATE('OCT-2013','MON-YYYY'), 'SUNDAY') + (2-1)*7;That's the 2nd Sunday after October 1; the 2nd Sunday of October is the 2nd Sunday after September 30, so you need to subtract 1 more day before calling NEXT_DAY.
    I'd do it this way:
    WHERE   c_date = NEXT_DAY ( TO_DATE ( '01-OCT-2013', 'DD-MON-YYYY') - 8
                             , 'SUNDAY'
                     ) + (7 * 2)     -- Last number is week numberRemember, calling NEXT_DAY like this depends on your NLS_DATE_LANGUAGE.
    and for next year Like
    UPDATE FILTERCALENDAR SET YEAR_WINDOW=1 WHERE c_date = add_months(NEXT_DAY( TO_DATE('OCT-2013','MON-YYYY'), 'SUNDAY') + (2-1)*7,+12)-1;If you want the 2nd Sunday in October, 2014, then take the previous expression, and just change 2013 to 2014:
    WHERE   c_date = NEXT_DAY ( TO_DATE ( '01-OCT-2014'     -- or any month and year you want
                                        , 'DD-MON-YYYY'
                            ) - 8
                             , 'SUNDAY'
                     ) + (7 * 2)     -- Last number is week number
    This is not an excellent way to do it as it does not take care of leap years and it does not scan and update values in the whole table for all years correctly.
    Can any one help me to resolve this please. 
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
    Explain, using specific examples, how you get those results from that data.
    See the forum FAQ {message:id=9360002}

  • Getting the data for the infotype 0006 and Subtype 4 in HR ABAP

    Hi All,
       I need to get the data from the info type 0006 and the subtype 4 , only i need to fetch the data in communications . Could you any one tell me best way to fetch that data.
    Thanks,
    SAP SAR.

    Write a select single on PA0006 for the given pernr begin and end dates and for subtype 4 ...
    select single * from PA0006
               where pernr = p_pernr
               and SUBTY = '0004'
               and ENDDA >= s_date-low
               and BEGDA <= s_date-high.

  • How to approach in getting the dates for the user given periods

    Hi All,
    I have areuirement where the calendar would be like as 466 for a period
    for eg. period 1(Jan) has 4 weeks
    period 2(Feb) has 6 weeks
    period 3(Mar) has 6 weeks
    again period 4(Apr) has 4 weeks
    period 5(May) has 6 weeks
    period 6(June) has 6 weeks
    How to get the dates (from date and end date) for the periods.
    Anybody's help will be appreciated
    Regards
    Saugata

    I have areuirement where the calendar would be like as 466 for a periodWhat does that mean? Is 466 the format of the data?
    The end date depends on the start date. This query might be helpful for you
    SQL> WITH data AS(
      2    SELECT 1 period, 4 duration FROM dual UNION ALL
      3    SELECT 2, 6 FROM dual UNION ALL
      4    SELECT 3, 6 FROM dual UNION ALL
      5    SELECT 4, 4 FROM dual UNION ALL
      6    SELECT 5, 6 FROM dual UNION ALL
      7    SELECT 6, 6 FROM dual)
      8  SELECT
      9    period,
    10    duration,
    11    SYSDATE + SUM(duration) OVER (ORDER BY period RANGE UNBOUNDED PRECEDING) * 7 AS end_date
    12  FROM data
    13  ;
        PERIOD   DURATION END_DATE
             1          4 16-NOV-07
             2          6 28-DEC-07
             3          6 08-FEB-08
             4          4 07-MAR-08
             5          6 18-APR-08
             6          6 30-MAY-08
    6 rows selected.
    SQL>

  • Get the yesterday or last month data

    Hi ,
    I've need a small help .
    This is the scenario.
    If today is 1st feb. so I need to get last month data.
    if today is 30 th i need to get the current month data before 30 I mean 29 days data.
    I have to do it automatically i mean i need to write case statement in my existing query by using sysdate and i have to get it .
    pls help me out . Your help is greatly appreciated.
    Thanks & Regards,
    madhav.

    Haven't tested it, but you could try something like
    This gives you last months data if executed on the first day of the month otherwise this months data until the day before today
    select *
    from my_table
    where my_date >= add_months(trunc(sysdate, 'MM'), sign(trunc(sysdate)-trunc(sysdate, 'MM'))-1)
    and   my_date <trunc(sysdate)After I read your posting again, I guess you wanted something else
    This query now gives you last months data if executed on the first day of the month otherwise the data of the day before today
    select *
    from my_table
    where my_date >= (case when trunc(sysdate) = trunc(sysdate, 'MM') then add_months(trunc(sysdate, 'MM'), -1) else trunc(sysdate-1) end)
    and   my_date <trunc(sysdate)Message was edited by:
    Jens Petersen

  • How do I get the data for this one?

    CF 7, SQL Server 2005
    I will try and explain this as clearly as possible, let me
    know if I failed and I will attempt to clear it up.
    The application keeps track of orders as they go through
    phases of production. Lets assume there are two phases of
    production, phase1 and phase2 with 3 statuses in each phase, new,
    open, complete. (depending on the phase an order can be in more
    than one phase at once.)
    There is a phase_log table which is a reference table that
    has a row for every time the order's status changes.
    Lets say the row in the phase_log table looks like this:
    phase_logID | OrderID | PhaseID | StatusID | etc...
    The main page will have a table for each phase, showing a
    list of the orders that currently have rows in the phase_log table
    for that phase. The kicker is, I only want to pull one row (the
    latest status change which will consequently be the highest status
    ID) for each order per phase.
    once I pull the data I guess I can populate a struct or
    array, but I am new to this and I can't figure out how to get the
    query/s I need to get it.
    Any help is appreciated,
    Thanks

    select phase_logid, orderid, phaseid, etc, max(statusid)
    status
    from yourtables
    where whatever
    group by phase_logid, orderid, phaseid, etc

  • To get the dates between a month

    Hi,
    i'm working in forms 6i and database 10g.
    i have a table named attendance which contains only the dates on which the employees are present.
    i need the dates on which the employees are absent when i give the date range.
    So how will I get the other days in a month if I give the start and end date of a month.
    I think u understood what I mean.
    Pls help..

    Rereading your post my guess is you're after something like below
    NOT TESTED ! I don't have database access
    select employee,the_date absent
      from (select x.employee,x.the_date,a.present_on
              from (select a.employee,md.the_date
                      from (select to_date(:yyyymm,'yyyymm') + level - 1 the_day
                              from dual
                            connect by level <= to_number(to_char(last_day(to_date(:yyyymm,'yyyymm')),'dd'))
                           ) md,  /* generating dates for a year_month given */
                           (select distinct employee
                              from attendance
                           ) a  /* retrieving all employees */
                   ) x,  /* cartesian join between employees and days in a month */
                   attendance a
             where x.employee = a.employee(+)
               and x.the_date = a.present_on(+)
    where present_on is nullRegards
    Etbin

  • Getting the date for the previous day

    How do I get the previous day's date with LabView 7.0? Is there a built in function that will allow me to do this (taking into account the number of days in a month, leap years etc) or do I have to write my own vi?
    Thank you,
    KB

    All you have to do is use the Get Date/Time in Seconds and then subtract the number of seconds in a day. The result is a time stamp that should account for everything.
    Attachments:
    Subtract_Day.jpg ‏4 KB

Maybe you are looking for

  • Filename attachment in E-Mail from Support Message

    Hello, Can You explain me how to manage a filename of the attachment in E-Mail  from Solution manager ServiceDesk. We receive the mail notification with attachment which has always same filename - "service_operation.pdf". Thank you.

  • Damaged file attachments for several users

    All of a sudden, a handful of people are reporting that file attachments on email are corrupted (jpegs with jagged lines in them, pdf files with garbled text, .sit and .zip files that don't open) and I'm not sure what the source of the issue is. Anyo

  • HACMP on non AIX systems

    Dear SDN , We are planning to implement SAP ECC HA solution . I need your openion on : 1 ) Can I use the High Availability Cluster Multi-Processing ( HACMP ) on non AIX systems ? for eg : we have Suse 10 with SP 1 2) I understood that in Distributed

  • Runing procedures from DBMS_STATS package - how ?

    Hello, i created account long time ago, but this is first time i need help. How can i run this code with PHP, and get results. In sql+ works fine - i made some attempts without any good results. {sql} variable num_rows number; variable num_blks numbe

  • Combining Sets of Books in EDW

    Hello, All: We're running Release 4.1 of the Oracle Embedded Data Warehouse (EDW). We have 12 companies that are each represented by a different set of books. One of those companies was recently moved into a different set of books for reasons not wor