Count Distinct employees between two dates

I'm having a headache trying to figure this out and I can't seem to find the correct way of doing it. Any help would be greatly appreciated.
I'm needing to get a distinct number count of weekly employees by month that have worked or received pay for the pay period that includes the 12th of the month. The employees should only be counted once per month even though they might have worked and gotten paid during the pay period that includes the 12th of the month. I will give below the column names an example of the data.
emp no_
00001
pay type_
week
pay period start date_
01-09-12
pay period end date_
01-15-12
pay date_
01-12-12
work date_
01-11-12

Hi,
housetiger77 wrote:
Thank you for your response. I'm working with Oracle Report Builder 10g. Your front-end tool can be significant, but it's much more important to know which database versions you have.
There is no version 10f or 10h, so it's kind of silly to say you have 10g. Give your real, full version, e.g. 10.2.0.4.0.
To find your database version, run
SELECT  *
FROM    v$version;The first line of output will have the database version.
The report will be grouped by month, state, and work location. For each work location it will give me the distinct number of employees who worked or received pay for the pay period which includes the 12th of the month.
The columns are as follows:
SELECT
phy_emp_no,
phy_date,
phy_actual_pay_date,
phy_ppr_period,
ppr_start_date,
ppr_end_date
FROM pyemppayhist, pycompayprd
where phy_prn_code = ppr_prn_code
and ppr_year = '2012'
and phy_tran_code = 'NWHR'
Below is my data example. I do not know how to put it in here without the rows and columns being all jumbled up. Sorry!That means you haven't read the forum FAQ yet. {message:id=9360002}
Take a couple of minutes to read it now; it will be a very good use of your time. What you need to do, including how to use \ tags to preserve formatting, is all explained in that message.  (Actually, it's not so inportant that your CREATE TABLE and INSERT statements be formatted, but it's esy to do, and you have to learn how to do it anyway to post your results.)
When you're ready to continue, post CREATE TABLE and INSERT statements for your sample data, the exact results you want from that data, and an explanation of how you get those results from that data.
What's wrong with the solutions you've already received?  Point out where they're getting the wrong results from your sample data, and explain how you might get the right results in those places.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • Extracting a count of distinct values between two date ranges over months

    Hi All,
    I am having a bit of difficulty in figuring out the query to build a list of active campaigns over a date range.
    i.e. I have a table with campaign IDs and their start and end date details like this
    Campaign_id     Start_date     End_date
            10001     1-Jun-09     31-May-11
            10002     1-Jun-09     23-Jun-11
            30041     21-Aug-09     31-Dec-09
            20005     3-Jun-10     31-May-11
            90021     21-Nov-09     30-Nov-10
            54000     1-Jun-11     1-Dec-12
            35600     1-Mar-10     31-Mar-12 What the above data means is, for eg. the campaign 10001 is active from 1-Jun-09 to 31-May-11 i.e. for 24 months (inclusive of the month Jun-09 and May-11)
    What I need to figure out is the counts of active campaigns between a date range and display that active count at a month level (for e.g. lets say we want to see all the campaigns that were active
    between the date range '01-JUN-2007' and '30-APR-2012' ). So the partial output would be as seen below. The list would continue till december-2012
    Month    Year    Count of active campaigns
    Jan    2009    0
    Feb    2009    0
    Mar    2009    0
    Apr    2009    0
    May    2009    0
    Jun    2009    2
    Jul    2009    2
    Aug    2009    3
    Sep    2009    3
    Oct    2009    3
    Nov    2009    4
    Dec    2009    4
    Jan    2010    3
    Feb    2010    3
    Mar    2010    4
    Apr    2010    4
    Dec    2012    1 Could anybody please help me with the right query for this.
    Thanks a lot for help
    Regards
    Goldi

    set pagesize 40
    with tab as
                    select 1 id, sysdate -100 start_date, sysdate end_date from dual
                    union
                    select 1 id, sysdate -200 start_date, sysdate -150 end_date from dual
                    union
                    select 1 id, sysdate -600 start_date, sysdate - 400 end_date from dual
                    union
                    select 1 id, sysdate -300 start_date, sysdate - 150 end_date from dual
                    union
                    select 2 id, sysdate -100 start_date, sysdate-50 end_date from dual
          year_tab as
                        select
                                 add_months(min_date, level -1) m
                        from
                                select min(trunc(start_date,'YYYY')) min_date, add_months(max(trunc(end_date,'YYYY')), 12) max_date
                                from tab
                        connect by level <= months_between(max_date, min_date)
    select to_char(m,'YYYY') year_,
             to_char(m,'Month') month_,
             nvl(act, 0) act
    from   year_tab,
                select m date_,count(*)  act
                from tab, year_tab
                where m between trunc(start_date,'MM') and trunc(end_date,'MM')
                group by m
                ) month_tab
    where m = date_(+)
    order by m;
    YEAR_ MONTH_           ACT
    2010  January            0
    2010  February           0
    2010  March              0
    2010  April              0
    2010  May                0
    2010  June               0
    2010  July               0
    2010  August             0
    2010  September          1
    2010  October            1
    2010  November           1
    2010  December           1
    2011  January            1
    2011  February           1
    2011  March              1
    2011  April              0
    2011  May                0
    2011  June               0
    2011  July               1
    2011  August             1
    2011  September          1
    2011  October            2
    2011  November           2
    2011  December           2
    2012  January            2
    2012  February           2
    2012  March              2
    2012  April              1
    2012  May                1
    2012  June               0
    2012  July               0
    2012  August             0
    2012  September          0
    2012  October            0
    2012  November           0
    2012  December           0
    36 rows selected.

  • Count days between two dates without weekend

    Hi,
    I need a solution in query or another thread, that returns the count of days between two dates without consider weekend (saturday and sunday) , I have the columns of type Date, and the return need in format of hours in one column hh:mm:ss and days in another column.
    Regards
    Jonas

    Hi and welcome to the forum.
    Keep in mind that you can do a search on this forum.
    Your question has been asked before.
    Some other pointers:
    http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:185012348071

  • How to count number of sundays between two dates

    Hi
    I want number of Sundays between two dates
    example
    number of Sundays count between '01-04-2013' and '30-04-2013' in one select query I have to include this as sub query in my select statement.

    Hi,
    ChakravarthyDBA wrote:
    Hi
    I want number of Sundays between two dates
    example
    number of Sundays count between '01-04-2013' and '30-04-2013' in one select query I have to include this as sub query in my select statement.Here's one way:
    SELECT       early_date
    ,       late_date
    ,       ( TRUNC (late_date + 1, 'IW')
           - TRUNC (early_date,        'IW')
           ) / 7       AS sundays
    FROM       table_x
    ;This does not depend on your NLS settings.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Point out where the statment above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Javascript anomoly on day count between two dates

    Using ApEx 4.0, I have found an anomoly in some javascript code that calculates the number of days between two dates, the current_date and the past_date. If the past-date is on or before March 10, 2013, and the current_date is between March 10, 2013, and November 3, 2013, the day count will be 1 day less than the actual count. Between November 3, 2013, and November 4, 2013, the count increments by 2, and then the count will be accurate from this date forward.
    Here are examples:
    Mar 10, 2013 = 69 days from 31-DEC-2012
    Mar 11, 2013 = 69 days from 31-DEC-2012
    Mar 12, 2013 = 70 days from 31-DEC-2012
    Nov. 3 2013 = 306 days from 31-DEC-2012
    Nov. 4 2013 = 308 days from 31-DEC-2012
    March 11 should be 70, and March 12 should be 71. November 3 should be 307, and November 4 corrects the wrong count which began March 11.
    Changing the past_date to March 10, 2013 produces the following:
    10-Mar-2013 = 0 days from 10-Mar-2013
    11-Mar-2013 = 0 days from 10-Mar-2013
    12-Mar-2013 = 1 days from 10-Mar-2013
    But changing the past_date to March 11, 2013, produces correct numbers:
    11-Mar-2013 = 0 days from 11-Mar-2013
    12-Mar-2013 = 1 days from 11-Mar-2013
    13-Mar-2013 = 2 days from 11-Mar-2013
    I would certainly appreciate anyone's help on identifying the cause of this anomoly. Here is the javascript code:
    var w1= ($v("P48_PAST_DATE"));
    w1 = (w1.toString());
    var vmon = (w1.substr(3,3));
    var vyr = (w1.substr(7));
    var r = (vyr.length);
    if (r == 2)
    vyr = (parseFloat(vyr) + 2000);
    var vday = (w1.substr(0,2));
    var y = (vmon.concat(" ",vday,", ",vyr));
    y = Date.parse(y);
    var w2 = ($v("P48_CURRENT_DATE"));
    var vmon2 = (w2.substr(3,3));
    var vyr2 = (w2.substr(7));
    var vday2 = (w2.substr(0,2));
    var x = (vmon2.concat(" ",vday2,", ",vyr2));
    x = Date.parse(x);
    var numdays = (x - y);
    numdays = (Math.floor(numdays / 86400000));
    $s("P48_NUMBEROFDAYS",numdays);

    Did you google for something like "javascript number of days between two dates". I think you will find the explanation in this observation:
    This method doesn't work properly if there's a daylight savings jump between the two dates.
    There are examples to be found to calculate the difference between two dates.

  • Count between two dates.

    dear friends
    i want fetch count between two dates.
    my query is like below.
    SELECT (to_date('19-mar-2012','dd-mm-yyyy')-to_date('01-apr-2012','dd-mm-yyyy')) FROM dual
    its given out like -13 but i want in positive mod like 13 only not '-' Sign.

    just use abs() function to your query to get the positive value
    SELECT abs(to_date('19-mar-2012','dd-mm-yyyy')-to_date('01-apr-2012','dd-mm-yyyy')) diff FROM dual

  • How to count the number of Fridays and Saturdays between two dates

    Hi every one ... If we want to count the number of Fridays and Saturdays between two dates, how would we do that ? !
    Dates are ( 11-Feb-2010) to (19-May-2010)
    how to do it in SQL
    Edited by: khalidoracleit on Jul 28, 2010 5:51 AM

    some nice coding here, I'm still amazed with what some people can do with "connect by". But I agree with some statements here that this can take "time", and to be honest, it's funny to see it working, but if you do not have a computer, just a calendar and some paper, would you go for "counting" so there must be a better solution?
    The best working math in here is done by Aketi Jyuuzou, who writes so good English that I wonder why he still insists that he doesn't ;-)
    Anyhow I "translated" that code to English, and I really like that math. Math is math and data is data.
    ALTER SESSION SET NLS_DATE_LANGUAGE='ENGLISH';
    WITH my_dates AS (
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100519','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100214','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100213','yyyymmdd') end_date FROM DUAL
    UNION ALL
    SELECT to_date('20100211','yyyymmdd') start_date,to_date('20100212','yyyymmdd') end_date FROM DUAL
    SELECT to_char(start_date,'DD.MM.YYYY') start_date,to_char(end_date,'DD.MM.YYYY') end_date,
           to_char(start_date,'DAY') start_weekday,to_char(end_date,'DAY') end_weekday,
           end_date-start_date day_difference,
           (next_day(end_date,'FRIDAY')-7
           -next_day(start_date -1,'FRIDAY'))/7+1
           +(next_day(end_date,'SATURDAY')-7
           -next_day(start_date -1,'SATURDAY'))/7+1 as count_of_fr_and_sat
    FROM my_dates;
    START_DATE END_DATE   START_WEEKDAY                        END_WEEKDAY                          DAY_DIFFERENCE         COUNT_OF_FR_AND_SAT   
    11.02.2010 19.05.2010 THURSDAY                             WEDNESDAY                            97                     28                    
    11.02.2010 14.02.2010 THURSDAY                             SUNDAY                               3                      2                     
    11.02.2010 13.02.2010 THURSDAY                             SATURDAY                             2                      2                     
    11.02.2010 12.02.2010 THURSDAY                             FRIDAY                               1                      1                      -- andy

  • How to count days between two dates excluding saterady and sunday

    Hi all
    iam working on oracle sql/plsql.
    In my application , i need to caliculate leave days between two dates excluding saterady and sunday
    Please tell me the solution if any one knows
    thanks in advance ,
    balu

    More modern version:
    WITH date_tab AS
    (SELECT TO_DATE ('&from_date', 'dd-MON-yyyy')
    + LEVEL
    - 1 business_date
    FROM DUAL
    CONNECT BY LEVEL <=
    TO_DATE ('&to_date', 'dd-MON-yyyy')
    - TO_DATE ('&from_date', 'dd-MON-yyyy')
    + 1)
    SELECT business_date
    FROM date_tab
    WHERE TO_CHAR (business_date, 'DY') NOT IN ('SAT', 'SUN');Thank you,
    Tony Miller
    Webster, TX
    Never Surrender Dreams!
    JMS
    If this question is answered, please mark the thread as closed and assign points where earned..

  • No of Fridays in between two date

    Hi all
    What is the Qucikest and easy way to retreive the NO of fridyas in betwen two dates
    Thanks & Regards
    Vivek

    vivekvm wrote:
    Hi all
    What is the Qucikest and easy way to retreive the NO of fridyas in betwen two dates
    Make sure you test the boundary conditions for any solution you get.
    Have you defined exactly what you mean by "in between two dates", for example. do you want to count the end points if one, or both, of them is a friday ?
    Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to Calculate number of months between two dates

    Hi All,
       In one of the fomr developments, I have to calculate the
    Number of Days
    Number of Months ( Considering Leap Year) provided by the dates, end user enters in the form,
    After going thorugh some forum discussion, I have come to know about so many things which were not clear till now.
    I have gone through various forums too,  some one suggets to make use of FORM CALC and some other JAVA SCRIPT. But the logic i want to build in java script.
    The most interesting point is the DATE object is not getting created when i write  the below code
      var startDate = new DATE(oYear, oMonth, oDay);
    I am still not clear, that really the date object gets created in Adobe form If so the why the alert box is getting populated when i write below lines
    var oTemp = startDate.getFullYear();
    xfa.host.messagebox(oTemp);
    So, there are so many unclear things,
    If any one can help me by suggesting the approach and how to build the logic in the JavaScript I would be really thankful
    Regards
    PavanChand

    Hi,
    ChakravarthyDBA wrote:
    Hi
    I want number of Sundays between two dates
    example
    number of Sundays count between '01-04-2013' and '30-04-2013' in one select query I have to include this as sub query in my select statement.Here's one way:
    SELECT       early_date
    ,       late_date
    ,       ( TRUNC (late_date + 1, 'IW')
           - TRUNC (early_date,        'IW')
           ) / 7       AS sundays
    FROM       table_x
    ;This does not depend on your NLS settings.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Point out where the statment above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • How to make search between two dates accept null not obligatory search proplem

    Hi guys when i search record between two dates it works ok success but you must enter date from and dateto first to  to make search
    i will show what i need from this example
    I need to search dynamic by 4 textbox
    1-datefrom
    2-dateto
    3-EmployeeNo
    4-EmployeeName
    but search i need must be dynamic meaning
    if i enter employee no only give me employee no found in database
    if i enter employee name give me employees found with this name using like
    if i enter all 4 text box null and enter button search get all data
    but i have proplem in this query when i need to search by click search button
    i must write date from and date to firstly then write employee no or employee name if i need to search
    so that i need to search by employee no alone or employee name alone without using date from and date to
    And if i search without using datefrom and dateto it give me message error 'string wasnot recognized as valid datetime"
    my stored procedure and code as following :
    ALTER proc [dbo].[CollectsearchData]
    @StartDate datetime,
    @EndDate datetime,
    @EmployeeID  NVARCHAR(50),
    @EmployeeName  nvarchar(50)
    as
    Begin
    Declare @SQLQuery as nvarchar(2000)
    SET @SQLQuery ='SELECT * from ViewEmployeeTest Where (1=1)'
    If (@StartDate is not NULL)
    Set @SQLQuery = @SQLQuery + ' And (joindate >= '''+ Cast(@StartDate as varchar(100))+''')'
    If (@EndDate is not NULL)
    Set @SQLQuery = @SQLQuery + ' And (joindate <= '''+ Cast(@EndDate as varchar(100))+''')' 
    If @EmployeeID <>''
    Set @SQLQuery = @SQLQuery + 'And (EmployeeID = '+ @EmployeeID+') '
    If @EmployeeName Is Not Null
    Set @SQLQuery = @SQLQuery + ' AND (DriverName LIKE
    ''%'+@EmployeeName+'%'') '
    Print @sqlQuery
    Exec (@SQLQuery) 
    End
    Function using
    public DataTable SearchDataA(string ConnectionString,string EmployeeNo,string EmployeeName, DateTime StartDate, DateTime EndDate)
    SqlConnection con = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "CollectsearchData";//work
    cmd.Parameters.Add("@StartDate", SqlDbType.DateTime);
    cmd.Parameters.Add("@EndDate", SqlDbType.DateTime);
    cmd.Parameters.Add("@EmployeeID", SqlDbType.NVarChar, 50);
    cmd.Parameters.Add("@EmployeeName", SqlDbType.NVarChar, 50);
    cmd.Parameters["@StartDate"].Value = StartDate;
    cmd.Parameters["@EndDate"].Value = EndDate;
    cmd.Parameters["@EmployeeID"].Value = EmployeeNo;
    cmd.Parameters["@EmployeeName"].Value = EmployeeName;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();
    da.Fill(ds);
    DataTable dt = ds.Tables[0];
    return dt;
    interface button search
     try
    CultureInfo ukCulture = new CultureInfo("en-GB");             
    FleetManagment.Fleet fleet = new FleetManagment.Fleet();
    DataTable Table = fleet.SearchDataA("Data Source=" + value1 + ";Initial Catalog=" + value2 + ";User ID=" + value3 + ";Password=" + value4 + "",textBox3.Text,textBox4.Text, DateTime.Parse(textBox1.Text,
    ukCulture.DateTimeFormat), Convert.ToDateTime(textBox2.Text, ukCulture.DateTimeFormat));
    dataGridView1.DataSource = Table;
    dataGridView1.Refresh();
    catch (Exception ex)
    MessageBox.Show(ex + "error");

    Yes, the below code should not be passed any value: (I am not sure of the syntax in .NET,Sorry) 
    --If startdate len is 0 - do not assign this value
    cmd.Parameters["@StartDate"].Value = StartDate;
    --If endate len is 0 - do not assign this value
    cmd.Parameters["@EndDate"].Value = EndDate;

  • Gap Between Two Dates

    Can Anyone tell me how to find out the gap between two dates. Specifically Without counting Saturday and Sunday.

    corlettk wrote:
    <intercession>
    Has anyone written a DateMath class?... it would be handy... the amount (and ugliness) of the code required to do elementary date mathematics with the raw Calendar is appaling.<recess>
    Isn't Java 7 supposed to cure all this headache?
    </recess>

  • Select entries between two dates by converting Unix timestamp in Oracle Dat

    Hi,
    I need to select the entries between two dates from an Oracle db. The Oracle db has a column with Unix timestamps. I use the following querry, but it doesnt seem to be working as desired.
    select count(*) from reporter_status where to_char(FIRSTOCCURRENCE, 'mm-dd-yy') between ('08-07-06') and ('08-08-06');
    FIRSTOCCURRENCE has the Unix timestamps.
    Could anyone help me out with this. Thank you for your help.

    Assuming that it is actually a UNIX timestamp, then it is the number of seconds since Jan 1, 1970, so you need something like:
    SELECT COUNT(*)
    FROM reporter_status
    WHERE TO_DATE('01-Jan-1970', 'dd-mon-yyyy') + (firstoccurrence/24/60/60)
                    BETWEEN TO_DATE('08-07-2006', 'mm-dd-yyyy') AND
                            TO_DATE('08-08-2006, 'mm-dd-yyyy');Did Y2K not teach us anything? Use 4 digit years.
    John

  • Select Between Two Dates ELSE

    I can't really seem to get this straightened out.
    SELECT distinct DATE, gross_total_return
    FROM WPI_ICL
    CASE Between '01-01-1980' AND '09-30-2008'
    AND description = 'Broad Market Index United States Property (US Dollar)'
    ELSE
    description = 'S&P United States Property Residential (US Dollar)'
    END
    So, if records are between two dates, select a certain description, ELSE select a different description.  I've tried IF...Then, and I've tried Case too.  So far, nothing has worked out.
    Can someone please give me a point in the right direction?
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Here's a working example:
    DECLARE @wpi_icl TABLE (date DATE, gross_total_return FLOAT, description1 VARCHAR(100), description2 VARCHAR(100))
    INSERT INTO @wpi_icl (date, gross_total_return, description1, description2)
    VALUES
    ('2008-09-29', 100.0, 'Broad Market Index United States Property (US Dollar)', 'S&P United States Property Residential (US Dollar)'),
    ('2008-10-01', 200.0, 'Broad Market Index United States Property (US Dollar)', 'S&P United States Property Residential (US Dollar)')
    SELECT date, gross_total_return,
    CASE WHEN date BETWEEN '1900-01-01' AND '2008-09-30' THEN description1
    ELSE description2
    END AS description
    FROM @wpi_icl
    From the code you posted, it seems you're unsure of the syntax of CASEs.
    There are two ways to use a case. The first is the example above. You enclose the conditions between CASE and END.
    Each condition has its own WHEN with a clause that evaluates to true or false. This clause can be made up of as many conditions as you like. After the clause comes a THEN. This is essentially what you want to happen if the clause returns true. WHEN/THEN is
    synonymous with IF/THEN in this instance.
    Including an ELSE is optional, but, be aware if you do not, and none of your WHEN clauses evaluate to true, you will have a NULL returned.
    CASE
    WHEN theseDriods = theDriodsWereLookingFor THEN callVader
    WHEN theseDriods <> theDriodsWereLookingFor THEN moveAlong
    ELSE goHomeAndRethinkLife
    END
    The other (less common) option operates like a SWITCH in some other languages. Its still surrounded by CASE and END but this time, the when just contains a value to be compared to the value at the start of the case:
    CASE 16
    WHEN 15 THEN 'too low'
    WHEN 16 THEN 'just right'
    WHEN 17 THEN 'too high'
    END
    Hope this helps.

  • Average of a field between two dates

    Hi,
    I have a table with two fields. Date Field and Percentage field. For ex,
    Date Percentage
    1/1/2006 11
    1/4/2006 23
    2/4/2006 34
    11/11/2006 354
    1/4/2007 75
    10/09/2007 67
    2/3/2008 876
    I want to find the average(sum of percentage/total no) of Percentage field between two dates.
    I am passing only the end date. And, the start date I have to find according to the end date.
    For ex,if I am passing the end date as 10/09/2007, starting date should be 1/4/2007.
    And, if I am passing the end date as 11/11/2006, starting date should be 1/4/2006.
    For end date 2/3/2008, start date should be 1/4/2007.
    Starting date is taken as by considering the year end as April to March. So, I have to retrieve the average of the percentage field from April to the selected date as end date.
    thanks

    Getting the sum, number of rows and average since the last 1st of April to the current date :
    SQL> with tbl as
      2  (select to_date('01/01/2006','dd/mm/yyyy') as dt, 11  prct from dual union all
      3   select to_date('01/04/2006','dd/mm/yyyy') as dt, 23  prct from dual union all
      4   select to_date('02/04/2006','dd/mm/yyyy') as dt, 34  prct from dual union all
      5   select to_date('11/11/2006','dd/mm/yyyy') as dt, 354 prct from dual union all
      6   select to_date('01/04/2007','dd/mm/yyyy') as dt, 75  prct from dual union all
      7   select to_date('10/09/2007','dd/mm/yyyy') as dt, 67  prct from dual union all
      8   select to_date('02/03/2008','dd/mm/yyyy') as dt, 876 prct from dual)
      9  select dt, prct,
    10         sum(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) sum_prct,
    11         count(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) nb_prct,
    12         avg(prct) over (order by dt range between dt-add_months(trunc(add_months(dt,-3),'yyyy'),3) preceding and current row) avg_prct
    13  from tbl;
    DT             PRCT   SUM_PRCT    NB_PRCT   AVG_PRCT
    01/01/06         11         11          1         11
    01/04/06         23         23          1         23
    02/04/06         34         57          2       28,5
    11/11/06        354        411          3        137
    01/04/07         75         75          1         75
    10/09/07         67        142          2         71
    02/03/08        876       1018          3 339,333333
    7 rows selected.Nicolas.

Maybe you are looking for