Query of month to date

<u></u>
Hi all,
i need to define a query to restrict the key figure base on month to date(current date") of this year, and the range of last year.
**let's say today i run the query, and today is 11 of Aug,so i want to get the this year's Month to date total sales(sales value from 01 of Aug till 11 of Aug);
and since 1 of Aug is Monday, and 11 of aug is the following week Thuesday.
***I also want to get last year's Month to date total sales(sales value from first week Monday of last year Aug, which is 2 of Aug 2004, till the second week Thuesday of last year Aug, which is 12 of Aug lsat year)-- altough soemtime, the first week Monday of last year may fall to end of July, it still calucation these way.
I know I should define few variabels to restricted the key figures, but i am not sure
--what function module I should use to get the first date of current month; and in which date of week(Sunday ,Monday or Tuesday..) it falls into?
-- what is the good way to get the query done.
Waiting for your adice,
Ping

I found one FM called:
RS_VARI_V_1_ACTUAL_MONTH 
it get the First day of current month.
""Lokale Schnittstelle:
*"       EXPORTING
*"             VALUE(P_DATE) LIKE  SY-DATUM
*"       TABLES
*"              P_INTRANGE STRUCTURE  RSINTRANGE
but i don't know how to use it, where i can get the first day  of current month imported?? how to use this P_INTRANGE table? could any one help to to write a sample code to show me.
Thank you a million!!
Ping

Similar Messages

  • Picking Month from Date in ABAP query

    Dear All,
    I want to pick month from date in a abap query but it is giving error "BDTER" is not a valid comparison operator. comparison operator.
    Where i am wrong my query is below.
    SELECT SUM( BDMNG ) AS BDMNGT FROM RESB INTO CORRESPONDING FIELDS OF IT_MRP
    WHERE MONTH( BDTER ) = '12'.
    With Regards
    Ashwani K Mathur

    Dear Deepankar,
    Thanks for reply.
    Date fomat is yy/mm/dd (like 20071231) after your suggestion i have modified query.
    SELECT SUM( BDMNG ) AS BDMNGT FROM RESB INTO CORRESPONDING FIELDS OF IT_MRP
    WHERE  BDTER+4(2)  = 12.
    but while compiling it is giving error Field "BDTER+4(2)" unknown.
    Please suggest.
    Ashwani K Maathur

  • QUERY TO PRINT THE DATE OF NEXT FRIDAY THAT IS SIX MONTHS FROM TODAY

    CAN ANY PLZ LET ME KNOW THE QUERY TO PRINT THE DATE OF NEXT FRIDAY THAT IS SIX MONTHS FROM TODAY.THE OUTPUT DATE FORMAT SHOULD BE AS SHOWN IN THE EXAMPLE.
    (Eg) : TODAY: 24-FEB-09          
    NEXT_FRIDAY_AFTER_SIX_MONTHS: 28-AUG-2009 (FRIDAY)
    USING DUAL TABLE

    Laurent Schneider wrote:
    yes, but when I create a view, I cannot guarantee that every client accessing this view will be using English, can I?You're in an environment where you can't guarentee that, I agree. I'm in an environment where I very luckily can guarentee it. But in general, I take your point *{:-)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Query for month start and end date

    Hi,
    I want to pick every month Start date and End Date. could anybody suggest what is the query for this.
    I need output
    Start Date End Date
    01/01/2011 31/01/2011
    01/02/2011 28/02/2011
    01/03/2011 31/03/2011
    01/04/2011 30/04/2011
    01/05/2011 .......

    Hi,
    SQL> select sysdate from dual;
    SYSDATE
    24-FEB-11
    SQL> select last_day(sysdate) from dual;
    LAST_DAY(
    28-FEB-11
    SQL> select last_day(sysdate),last_day(add_months(sysdate,-1))+1 from dual;
    LAST_DAY( LAST_DAY(
    28-FEB-11 01-FEB-11
    SQL> select last_day(sysdate),last_day(add_months(sysdate,-2))+1 from dual;
    LAST_DAY( LAST_DAY(
    28-FEB-11 01-JAN-11Try to refer to Oracle documentation and try to experiments the functions, you will get results on your hand.
    - Pavan Kumar N
    Edited by: Pavan Kumar on Feb 24, 2011 12:51 PM
    Edited by: Pavan Kumar on Feb 24, 2011 12:52 PM

  • Month-to-Date and Year-to-Date values in Query

    Hello experts,
    One of our BI reports has the following requirement: the user should be asked for the report date. After the user inputs the date, the report shows the key figures in three different "flavors": one is the values for that date, the second one is the cumulate values from the first day of the month of the report date to the report date itself, and the third is the cumulate values from the first day of the year of the report date to the report date itself.
      I created my report date variable based on 0CALDAY. Then I searched for SAP-exit variables that would help me achieve this, but could not really find any, except for 0P_ABO10, 0P_ABO11, 0P_ABO12 variables, all of them have as description "Start of Key Date Year". I tried creating a few selections in which the dates taken were defined as a range from each of these variables to the report date variable (for the year-to-date values), but I got the error "Variable 0P_ABO10 could not be substituted". I also got this error for the other two variables. And I could not find any SAP-exit variables like "Start of Key Date Month", in order to do the Month-to-Date part. My next try was to use the field "Key Date" with a variable in it, instead my own report date variable based on 0CALDAY, but it gave me the same errors.
    I searched the forums and found a few threads that looked useful, like
    First and Last day of month and
    1st day of month / 1st day of week variables
    However, they require some ABAP coding, and I do not know where to place the code (actually, I do not know where to work with ABAP code), and I also believe that I would have to do some changes to it.
    Any suggestions?

    Hi Pedro,
    You have to create customer exit in T_Code: CMOD
    1. Create a Z project
    2. Select RSR00001 as enhancement type.
    3. Go into include ZXRSRU01
    4. create a code like
    Here A is your variable based on 0calmonth with type customer exit and B is variable for 0calday.
    Try to write logic for your case taking this as example.
    WHEN 'A'.
        IF I_Step = 2.
          Loop at I_T_VAR_RANGE into L_T_VAR_RANGE where VNAM = 'B'.
            Concatenate L_T_VAR_RANGE-LOW(4) '001' into D1.
            Concatenate L_T_VAR_RANGE-LOW(4) '012' into D2.
            Clear L_S_Range.
            L_S_Range-low = D1.
            L_S_RANGE-high = D2.
            L_S_RANGE-sign = 'I'.
            L_S_RANGE-opt = 'BT'.
            Append L_S_Range to E_T_Range.
          ENDLOOP.
        ENDIF.
    If you want exact code I can help you in that.
    Thanks,
    Kams

  • Last 6 months of data from current date

    Hi Experts,
    I have a requirement in WebI to display last 6 months of data based on current date.Actually I have a column called "Employee Contract Start date" in my report.Suppose the end user executes the report today,then he should be able to see the Employee's data whose contract started today and in the last 6months from current date.
    Also I have dimension object name "Employee Contract Start Date".
    Please be noted that I am getting the data from Bex Query and I am working on BO 4.1 version.
    I have Objects "Calender day" , "Cal.year/Month" , "Calender month" , "Employee Contract Start Date" in the BEx Query.
    Could anyone please propose me, what are the ways to meet this requirement?

    Hi Cris,
    We can get the 6 Months date in webi.
    Check the below blog , will help you.
    http://scn.sap.com/community/businessobjects-web-intelligence/blog/2014/01/21/time-variablesdimensions
    Regards,
    Javed

  • Select records based on monthly anniversary date

    Hi,
    I have a table with a date_added field and I want to select records based on the monthly anniversary date of this field.
    eg. ID, Date_added
    1, 10-DEC-2012
    2, 11-NOV-2012
    3, 10-MAR-2012
    4, 28-FEB-2012
    5, 30-DEC-2012
    So For the 10th of Jan 2013, I would want to return records 1 and 3 only
    I started looking at the extract function, but this soon falls down for records at the end of the month. For example, on the 28th Feb, I would also want to include records where the date_added day is the 29th, 30th or 31st. So, in the table above I would want to return records 4 and 5, but extract would only return 4.
    Is there a simple function to do this month anniversary query - am I missing something very obvious? Or, do I need to write a query to explicitly cope with dates at the end of the month? So far I haven't found a sensible simple solution!
    I'm using 11g
    thanks

    I didn't look into leap year, but this should give you a starting point:
    select  *
      from  t
      where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
                  when to_date(:target_date,'mmddyyyy')
                    then case
                           when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
                             then 1
                         end
                  else case
                           when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
                             then 1
                         end
                end
    /For example, target date is 1/10/2013:
    SQL> variable target_date varchar2(8)
    SQL> exec :target_date := '01102013';
    PL/SQL procedure successfully completed.
    SQL> with t as (
      2             select 1 id,to_date('10-DEC-2012','dd-mon-yyyy') date_added from dual union all
      3             select 2,to_date('11-NOV-2012','dd-mon-yyyy') from dual union all
      4             select 3,to_date('10-MAR-2012','dd-mon-yyyy') from dual union all
      5             select 4,to_date('28-FEB-2012','dd-mon-yyyy') from dual union all
      6             select 5,to_date('30-DEC-2012','dd-mon-yyyy') from dual
      7            )
      8  select  *
      9    from  t
    10    where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
    11                when to_date(:target_date,'mmddyyyy')
    12                  then case
    13                         when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
    14                           then 1
    15                       end
    16                else case
    17                         when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
    18                           then 1
    19                       end
    20              end
    21  /
            ID DATE_ADDE
             1 10-DEC-12
             3 10-MAR-12
    SQL> And target date is 2/28/2013:
    SQL> exec :target_date := '02282013';
    PL/SQL procedure successfully completed.
    SQL> with t as (
      2             select 1 id,to_date('10-DEC-2012','dd-mon-yyyy') date_added from dual union all
      3             select 2,to_date('11-NOV-2012','dd-mon-yyyy') from dual union all
      4             select 3,to_date('10-MAR-2012','dd-mon-yyyy') from dual union all
      5             select 4,to_date('28-FEB-2012','dd-mon-yyyy') from dual union all
      6             select 5,to_date('30-DEC-2012','dd-mon-yyyy') from dual
      7            )
      8  select  *
      9    from  t
    10    where 1 = case last_day(to_date(:target_date,'mmddyyyy'))
    11                when to_date(:target_date,'mmddyyyy')
    12                  then case
    13                         when to_char(date_added,'dd') >= to_char(to_date(:target_date,'mmddyyyy'),'dd')
    14                           then 1
    15                       end
    16                else case
    17                         when to_char(date_added,'dd') = to_char(to_date(:target_date,'mmddyyyy'),'dd')
    18                           then 1
    19                       end
    20              end
    21  /
            ID DATE_ADDE
             4 28-FEB-12
             5 30-DEC-12
    SQL> SY.

  • Previous month first data and previous month last date

    can any body have query to get previous month first date and previous month last date.
    Ex: First day of the previous week:
    TIMESTAMPADD(SQL_TSI_DAY,-6, (TIMESTAMPADD(SQL_TSI_DAY, DAYOFWEEK(CURRENT_DATE) *-1,CURRENT_DATE)))
    Last day of the previous week:
    TIMESTAMPADD(SQL_TSI_DAY, DAYOFWEEK(CURRENT_DATE) *-1,CURRENT_DATE)
    can anybody have it for first day of the previous month,last day of the previous month?
    Edited by: user12255470 on Apr 7, 2010 3:30 AM

    Hi,
    1st day of previous month :
    TIMESTAMPADD(SQL_TSI_DAY, ( DAYOFMONTH(TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)) * -1) + 1, TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE))
    last day of previous month :
    TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)) * -1 , TIMESTAMPADD(SQL_TSI_MONTH, 1, TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)))
    Please mark Q answered and award points for correct answers !
    Thanks
    Alastair

  • MTD(Month To Date) and YTD(Year To Date) with one example

    can any ont Explain about MTD(Month To Date) and YTD(Year To Date) with one example plz

    Hi,
    Can you please elaborate.
    MTD is from the 1st of the current month till today's date.
    YTD is from 1st Jan till today's date.
    If you trying to build this is query. Create restricted key figure and put restriction on calday with a customer exit for the same.
    Thanks,
    S

  • 12 months AGO date

    i have a ccan_dt(connection cancellation date) for every agent
    i am trying to calculate the amount the agents spend before 12 months of connection cancellation date ie ccan_dt
    agent ccandt
    a 14/8/2009
    b 12/7/2003
    c 08/10/2000
    d 7/8/1999
    select sum(spend),agent from spendmas where spenddt between d1 and d2 group by agent
    in the above d2 is the ccan_dt of each agent and d1 is 12 before date of d2
    can any one suggest the efficinet way of acheving this.
    i did this by creating a temp table to hold the dates and then calculated the spend.
    but how can i achevie this with out creating a temp table.
    is there any regular expression which can get 12 months ago date as in OBIEE.
    please advice..

    user633377 wrote:
    select sum(spend),agent from spendmas where spenddt between d1 and d2 group by agent
    in the above d2 is the ccan_dt of each agent and d1 is 12 before date of d2
    can any one suggest the efficinet way of acheving this.
    i did this by creating a temp table to hold the dates and then calculated the spend.
    but how can i achevie this with out creating a temp table.
    is there any regular expression which can get 12 months ago date as in OBIEE.
    please advice..Didn't quiet understand the need for a temp table.
    However you can get a date from 12 months before by using ADD_MONTHS Function.
    Something like:
    SQL> SELECT SYSDATE FROM Dual
      2  /
    SYSDATE
    20-AUG-09
    1 row selected.
    SQL> SELECT ADD_MONTHS(sysdate, -12) FROM Dual
      2  /
    ADD_MONTH
    20-AUG-08
    1 row selected.
    SQL>So your query might be changed to
      SELECT   SUM (spend), agent
        FROM   spendmas
       WHERE   spenddt BETWEEN d2 AND ADD_MONTHS (d2, -12)
    GROUP BY   agentAssumed d2 is cancellation date
    Hope this helps.
    Regards,
    Jo

  • Querying / Reporting on Install Date of Office Applications

    I am trying to create a query/report that looks for recently installed applications that require extra licensing costs from Microsoft, including Visio and Project.  I've made some really good reports for what applications are installed on what machines,
    but where everything breaks down is the install date.  Since Office applications are patched monthly, the install date reported by our inventory changes each time the applications patch.  This gives me reports that seem to think that hundreds of
    users have installed these applications in the last month.
    The install date in both the Installed Software and Installed Applications classes shows the date of the last update installation, not the original installation.  
    On sample machines, Programs and Features shows the correct original installation date, but I can't find where that date is coming from.  I have checked HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall, HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall,
    and HKLM\Software\Classes\Installer\Products, and the install date shown is the date the application was last updated.
    Any ideas on how to collect the correct install date by expanding my hardware inventory?  Or create a better query to use the data I have, possibly the History classes?

    On a single test machine, I found a match, for the date displayed in "Installed Programs" vs. "Installed Updates"
    This string/value seems to have the correct date (but it could be complete coincidence).
    I theorised that the date against this specific Office Setup component, could be static (but who really knows. it's just a guess on my part.)
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{90150000-0116-0409-1000-0000000FF1CE} | InstallDate
    Don
    (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable.
    This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

  • Extracting month from date

    hi,
    I have a query in Informix which get the month part of a date. Please help me in converting the same to oracle.
    Informix query
    select month(col1 - today) from tab1;
    col1 is a date field, today will yield the current date and month function will get the month of the date.
    In oracle, when we subtract two dates we will get a number value, how to convert that back to date and extract the month part.
    Help me?????
    Regards,
    Gopu

    select months_between(sysdate, col1)
    from tab1;
    This will return a decimal value representing the months and part month between the two periods. The later date should be specified first, or the result will be a negative value.

  • BC4J Query by example for dates uses wrong date format

    When querying by example on date fields, I get the following nested exceptions:
    oracle.jbo.SQLStmtException: JBO-27121: SQL error during statement execution.
    JBO-26044: Error while getting estimated row count for view object
    and
    java.sql.SQLException: ORA-01830: date format picture ends before converting entire input string.
    It would seem to be caused by the following clause added to the end of the entity object's query:
    "QRSLT WHERE ( ( (DATE_FIELD = TO_DATE('23/12/2003', 'yyyy-mm-dd')) ) )"
    which causes problems as our entity objects use a 'dd/MM/yyyy' date format.
    Is there a way we can make the query by example use the same date format as the rest of our app?

    I‘m not an expert on this but I see nobody is replying so this might help you. I've been having problems with dates as well and I‘m pretty sure that the attached formatter isn't used in find mode. That is because the java date class (can't remember which one) used by the BC4J has the format yyyy-mm-dd. I don't now if it is possible to change it but I got around the problem by writing my own domain. You can take a look at Toystore demo, by Steve Muench, that uses a custom date domain, ExpirationDate (see the code below). It is mapped to a VARCHAR column in the database but it is possible to map it to a DATE column.
    I have been watching the postings with questions about dates and I have noticed that a lot of people have problems with this but I haven’t seen an answer yet.
    package toystore.model.datatypes.common;
    import java.io.Serializable;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import oracle.jbo.Transaction;
    import oracle.jbo.domain.DataCreationException;
    import oracle.jbo.domain.DomainInterface;
    import oracle.jbo.domain.DomainOwnerInterface;
    // --- File generated by Oracle Business Components for Java.
    * This custom datatype implements an immutable domain class that
    * maps to a VARCHAR column containing values like '10/2004' representing
    * expiration dates of credit cards. We could have chosen to implement
    * this as a domain that stores itself in a DATE column instead of a
    * VARCHAR column, but since the Java Pet Store demo schema stored the
    * information in a VARCHAR column, we decided to illustrate how to
    * accommodate that case using domains.
    public class ExpirationDate implements DomainInterface, Serializable {
    private Date mDate;
    private String mDateAsString;
    protected ExpirationDate() {
    mDate = new Date();
    convertDateToStringFormat();
    * Return the value of the expiration date as a java.util.Date
    public Date getDateValue() {
    return mDate;
    * Allow expiration date to be constructed from two
    * strings representing month and year
    public ExpirationDate(String monthVal, String yearVal) {
    this(monthVal+'/'+yearVal);
    public ExpirationDate(String val) {
    validate(val);
    convertDateToStringFormat();
    * The getData() method must return the type of object that JDBC will
    * see for storage in the database. Since we want this ExpirationDate
    * datatype to map to a VARCHAR column in the database, we return the
    * string format of the date
    public Object getData() {
    return mDateAsString;
    * <b>Internal:</b> <em>Applications should not use this method.</em>
    public void setContext(DomainOwnerInterface owner, Transaction trans, Object obj) {
    * Performs basic validation on strings that represent expiration dates
    * in the format of MM/YYYY. Note that in the process of testing whether
    * the string represents a valid month and year, we end up setting
    * the private member variable mDate with the date value, so if the
    * validate() method does not throw an exception, the mDate will be setup.
    protected void validate(String val) {
    if (val != null) {
    if (val.length() != 7 ||
    val.charAt(2) != '/' ||
    !isAllDigitsExceptSlashAtPositionTwo(val) ||
    !isValidMonthAndYear(val)) {
    throw new DataCreationException(ErrorMessages.class,
    ErrorMessages.INVALID_EXPRDATE,
    null,null);
    * Returns true if all digits except position 2 (zero-based) are digits
    private boolean isAllDigitsExceptSlashAtPositionTwo(String val) {
    for (int z=0, max = val.length(); z < max; z++) {
    if (z != 2 && !Character.isDigit(val.charAt(z))) {
    return false;
    return true;
    * Returns true if the val string, assumed to be in "MM/YYYY" format
    * is a valid month and year value, setting the mDate member variable
    * if they are valid.
    private boolean isValidMonthAndYear(String val) {
    try {
    int month = Integer.parseInt(val.substring(0,2));
    int year = Integer.parseInt(val.substring(3));
    Calendar c = Calendar.getInstance();
    c.setLenient(false);
    c.set(year,month-1,1); // Month is zero-based !
    mDate = c.getTime();
    catch (IllegalArgumentException i) {
    return false;
    return true;
    public String toString() {
    return mDateAsString;
    * Convert mDate to String format
    private void convertDateToStringFormat() {
    if (mDate != null) {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
    mDateAsString = sdf.format(mDate);
    * Return true if the expiration date is in the future
    public boolean isFutureDate() {
    return mDate.compareTo(new Date())> 0;
    * Compare the Expiration Dates by comparing their respective
    * getData() values
    public boolean equals(Object obj) {
    if (obj instanceof DomainInterface) {
    Object thisData = getData();
    if (thisData != null) {
    return thisData.equals(((DomainInterface)obj).getData());
    return ((DomainInterface)obj).getData() == null;
    return false;

  • Last month with data  - BEx variable

    Hi guys,
    I am using in the query the char 0CALMONTH to restrict the KF amount, just to get the last month of data that was loaded in the infocube. I tried with content variables but none of them are working. I used 0CYMONTH or 0CMLMON.
    the only thing that I want is to get from the cube always the last month with data that was loaded.
    Do I need to create a customer exit? does anyone has the code to give me?
    any help¡?
    thank u.
    E.V.

    Hi,
    two alternatives:
    VarExit: perform a select statement on your cube joined with your time dimension; or even directly on your time dimension something like:
    SELECT MAX(SID_0CALMONTH) FROM /BIC/D<cube>T.
    This will give the last CALMONTH with posted data in absolute (not considering your query selection)
    <i>Replacement path variable based on a query: create a query which has to return one record an 0CALMONTH in the columns. Put a TOP1 condition on one of your KeyFig. In your original query restrict 0CALMONTH with a variable of type replacement path on the TOP1 query. The advantage of this alternative is that you can get the last CALMONTH posted with data RELATIVE to your query selections if you move your variables input from the user to the TOP1 query...</i>
    Sorry, the above won't work it out; I just has the same requirement and implemented the varexit reading the time dim table.
    hope this helps....
    Olivier.
    Message was edited by:
            Olivier Cora

  • Need a query for monthly Report

    Hello All,
    I need a query for monthly report,
    comp_code
    emp_id
    dept_id
    work_day
    100
    A100
    MECH
    01/01/2013
    100
    A100
    MECH
    02/01/2013
    100
    A100
    MECH
    03/01/2013
    100
    A100
    MECH
    04/01/2013
    100
    A100
    MECH
    05/02/2013
    100
    A100
    MECH
    08/02/2013
    100
    A100
    MECH
    09/02/2013
    100
    A100
    MECH
    10/02/2013
    100
    A100
    MECH
    12/05/2013
    100
    A100
    MECH
    13/05/2013
    100
    A101
    CIV
    01/04/2013
    100
    A101
    CIV
    02/04/2013
    100
    A101
    CIV
    03/04/2013
    100
    A101
    CIV
    04/04/2013
    100
    A101
    CIV
    06/04/2013
    100
    A101
    CIV
    06/06/2013
    100
    A101
    CIV
    07/06/2013
    100
    A101
    CIV
    08/06/2013
    100
    A101
    CIV
    09/06/2013
    100
    A101
    CIV
    10/06/2013
    100
    A101
    CIV
    11/12/2013
    100
    A101
    CIV
    12/12/2013
    100
    A101
    CIV
    13/12/2013
    100
    A101
    CIV
    14/12/2013
        Dear friends this the sample table of my report.In which table has contain list of  employees with their working days(actual table has contain almost 5laks of records).
    suppose user choose the date between 01/01/2013 and 31/12/2013 then the result should be like this.
    comp_code
    emp_id
    dept_id
    month
    Total_work
    100
    A100
    MECH
    JANUARY
    4
    100
    A100
    MECH
    FEBRUARY
    2
    100
    A100
    MECH
    MARCH
    0
    100
    A100
    MECH
    APRIL
    0
    100
    A100
    MECH
    MAY
    2
    100
    A100
    MECH
    JUNE
    0
    100
    A100
    MECH
    JULY
    0
    100
    A100
    MECH
    AUGUST
    0
    100
    A100
    MECH
    SEPTEMBER
    0
    100
    A100
    MECH
    OCTOBER
    0
    100
    A100
    MECH
    NOVEMBER
    0
    100
    A100
    MECH
    DECEMBER
    0
    100
    A101
    CIV
    JANUARY
    0
    100
    A101
    CIV
    FEBRUARY
    0
    100
    A101
    CIV
    MARCH
    0
    100
    A101
    CIV
    APRIL
    5
    100
    A101
    CIV
    MAY
    0
    100
    A101
    CIV
    JUNE
    5
    100
    A101
    CIV
    JULY
    0
    100
    A101
    CIV
    AUGUST
    0
    100
    A101
    CIV
    SEPTEMBER
    0
    100
    A101
    CIV
    OCTOBER
    0
    100
    A101
    CIV
    NOVEMBER
    0
    100
    A101
    CIV
    DECEMBER
    4

    Hi,
    If you want the output to include months where no work was done (with 0 in the total_work column) then you need to outer-join a "table" that has one row per month, and make it a partitioned outer join:
    WITH  got_end_points   AS
       SELECT  TRUNC (MIN (work_day), 'MONTH')   AS first_month
       ,       TRUNC (MAX (work_day), 'MONTH')   AS last_month
       FROM    table_x
    ,   all_months   AS
       SELECT  ADD_MONTHS (first_month, LEVEL - 1)   AS a_month
       ,       ADD_MONTHS (first_month, LEVEL)       AS next_month
       FROM    got_end_points
       CONNECT BY  LEVEL <= 1 + MONTHS_BETWEEN (last_month, first_month)
    SELECT    t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    ,         COUNT (t.work_day) AS total_work
    FROM             all_months  m
    LEFT OUTER JOIN  table_x     t  PARTITION BY (t.comp_code, t.emp_id, t.ept_id)
                                    ON   t.work_day  >= a.a_month
                                    AND  t.work_day  <  a.next_month
    GROUP BY  t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    ORDER BY  t.comp_code
    ,         t.emp_id
    ,         t.dept_id
    ,         m.a_month
    As posted, this include every month that is actually in the table.  You can change the first sub-query if you want to enter first and last months.
    I hope this answers your question.
    If not, post  a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Point out where the query above is giving the wrong results, and explain, using specific examples, how you get the correct results from the given data in those places.  If you changed the query at all, post your code.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

Maybe you are looking for