Single day date range query

I have a table with a created_date column. The datatype is DATE.
When i query this table for some date range I do not ever get any results for a single day.
e.g. select * from table where created_date >='29-Dec-2009' and created_date <='30-Dec-2009'.
Result set = 5 records
However,
select * from table where created_date >='29-Dec-2009' and created_date <='29-Dec-2009'.
OR
select * from table where created_date >='30-Dec-2009' and created_date <='30-Dec-2009'.
yield 0 records.
Why is this so? I seem to be missing something obvious. Any pointers would be really helpful

select * from table where created_date >='29-Dec-2009' and created_date <='30-Dec-2009'.means all created date between '29-Dec-2009 00:00:00' and '30-Dec-2009 00:00:00'
select * from table where created_date >='29-Dec-2009' and created_date <='29-Dec-2009'.means all created date between '29-Dec-2009 00:00:00' and '29-Dec-2009 00:00:00'
select * from table where created_date >='30-Dec-2009' and created_date <='30-Dec-2009'.means all created date between '30-Dec-2009 00:00:00' and '30-Dec-2009 00:00:00'
So you need to correctly manage the time...
select * from table where created_date >='29-Dec-2009' and created_date &lt; '30-Dec-2009'.To get only records at any time during Dec-29.
select * from table where created_date >='30-Dec-2009' and created_date &lt; '31-Dec-2009'.To get only records at any time during Dec-30.
select * from table where created_date >='29-Dec-2009' and created_date &lt; '31-Dec-2009'.To get only records at any time during Dec-29 and Dec-30.
Max
[My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/29/estrarre-i-dati-in-formato-xml-da-sql/]

Similar Messages

  • Date range query between day1 and day1-14

    I am using:
    Oracle SQL Developer (3.0.04)
    Build MAin-04.34
    Oracle Database 11g
    Enterprise Edition 11.2.0.1.0 - 64bit Production
    I am having diffitult time getting this filter to work:
    {Code}
    where date_value between :day1 and :day1 - 14
    {Code}
    What am I doing wrong?
    I am looking to input a single day and have it give a range of 14 days back. So if I put "25-JUN-2013" it should include that day and track back 14 days.

    1007410 wrote:
    where date_value between :day1 and :day1 - 14
    Reverse the order.
    You generally specify a range from LOW to HIGH. Or in dates, EARLIER to LATER.
    You've done the reverse.
    Basically instead of saying "Pick a number from 1 to 10", you said "Pick a number from 10 to 1".
    with xx as
       ( select to_date('25-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('20-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('15-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('05-jun-2013', 'dd-mon-yyyy') d from dual
    Select d
      from xx
    where d between sysdate and sysdate-14 ;
    no rows selected.
    with xx as
       ( select to_date('25-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('20-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('15-jun-2013', 'dd-mon-yyyy') d from dual union all
         select to_date('05-jun-2013', 'dd-mon-yyyy') d from dual
    Select d
      from xx
    where d between sysdate-14 and sysdate;
    D       
    25-JUN-13
    20-JUN-13
    15-JUN-13
    3 rows selected.

  • Date Ranges Query

    Hi Experts,
    A very happy new year to all of you(to some in advance)!!
    I have a table where I have the employee id and task assigned with start dates & end dates. Overlapping dates of tasks is a data issue however I know how to spot them & eradicate them. So there will be no overlapping task dates
    Employee_id
    Task_No
    Task_Start_date
    Task_End_Date
    Sample Data
    1     T1     01-Jan-2014     28-Feb-2014
    1     T2     01-Mar-2014     31-Dec-2014
    2     T1     23-Jan-2014     31-Dec-2014
    2     T2     01-Jan-2015     31-Dec-2073 (Means end of time)
    3     T3     01-Jan-2014     15-Jul-2014
    3     T4     01-Aug-2014     31-Dec-2014
    4     T5     01-Jan-2014     31-Dec-2073
    I want to devise a query where i provide the end date & it will list out all the employees who are free for even one day starting 01-Jan-2014. So for example If I give 31-Dec-2014, it will list out
    EmpId     (First day on which the employee is free)
    2               01-Jan-2014
    3               16-Jul-2014
    If I give end date = end of time(31-Dec-2013), Expected Result -
    EmpId     (First day on which the employee is free)
    1               01-Jan-2015
    2               01-Jan-2014
    3               16-Jul-2014
    If I give end date = 31 Jan 2014, Expected Result -
    EmpId     (First day on which the employee is free)
    1               01-Jan-2015
    I devised following query, however it does not catch employee id 2. Also it does not provide flexibility to change end date-
    select *
      from (select employee_id,
                   task_start_date,
                   task_end_date,
                   lag(task_end_date, 1, task_start_date) over(partition by employee_id order by task_start_date) prev_end_date
              from shop.employee_tasks
             where task_end_date >= trunc(sysdate))
    where task_start_date - prev_end_date > 1
    Thanks in advance!!
    Regards,

    This is an example of what I call the "free time" query: you have the dates when you are busy and you want the dates when you are free.
    You can find a beautiful solution to the basic problem here: Ask Tom "SQL Query to find gaps in date ranges" (search for Antony Boucher's solution). Please note that this solution works even with overlapping date ranges.
    To apply the solution here, first create the test data (please do this yourself in later questions).
    create table t(Employee_id, task_no, Task_Start_date, task_end_date)
    as select
    1, 'T1', to_date('01-jan-2014'), to_date('28-feb-2014') from dual union all select
    1, 'T2', to_date('01-Mar-2014'), to_date('31-Dec-2014') from dual union all select
    2, 'T1', to_date('23-jan-2014'), to_date('31-dec-2014') from dual union all select
    2, 'T2', to_date('01-jan-2015'), to_date('31-dec-2073') from dual union all select
    3, 'T3', to_date('01-jan-2014'), to_date('15-jul-2014') from dual union all select
    3, 'T4', to_date('01-aug-2014'), to_date('31-dec-2014') from dual union all select
    4, 'T5', to_date('01-Jan-2014'), to_date('31-Dec-2073') from dual;
    In the query, you have to add records for yesterday and for the "end date" you want. This allows you to find "free time" before and after the date ranges in your table.
    Now you partition by Employee_id and order by Task_Start_date. Using the max(task_end_date) analytic function, you get the latest end date up to now. Add 1 to this and you get the first free date (maybe). To make sure that date is free, it has to be before the next start date.
    variable end_date varchar2(64)
    exec :end_date := '31-Dec-2073';
    with boundaries as (
      select trunc(sysdate)-1 task_start_date, trunc(sysdate)-1 task_end_date from dual
      union all
      select to_date(:end_date)+1, to_date(:end_date)+1 from dual
    ), data as (
      select * from t
    where task_end_date >= trunc(sysdate)
      and task_start_date < :end_date
      union all
      select distinct a.employee_id, null, b.task_start_date, b.task_end_date
      from t a, boundaries b
    select employee_id, min(free_start) free_start
    from (
      select employee_id,
      max(task_end_date) over (partition by employee_id order by task_start_date)+1 free_start,
      lead(task_start_date) over (partition by employee_id order by task_start_date)-1 free_end
      from data
    where free_start <= free_end
    group by employee_id;
    EMPLOYEE_ID
    FREE_START
    1
    01-JAN-15
    2
    01-JAN-14
    3
    16-JUL-14

  • Date range query  problem  in report

    Hi all,
    I have created a report based on query and i want to put date range selection but query giving problem.
    If i am creating select list selection then it is working fine means it will display all records on the particular date.
    But what i need is that user will enter date range as creation_date1,creation_date2 and query should return all the records between these date range. i want to pass it by creating items, i created two items and passing creation_date range to display all records but not displaying and if not passing date then should take null as default and display all records
    Here is the query:
    /* Formatted on 2006/12/10 20:01 (Formatter Plus v4.8.0) */
    SELECT tsh."SR_HEADER_ID", tsh."SALES_DEPT_NUMBER", tsh."COUNTRY",
    tsh."LOCAL_REPORT_NUMBER", tsh."ISSUE_DATE", tsh."SUBJECT",
    tsh."MACHINE_SERIAL_NUMBER", tsh."MACHINE_TYPE", tsh."MACHINE_HOURS",
    tsh."STATUS"
    FROM "TRX_SR_HEADERS" tsh, "TRX_SR_PARTS" tsp
    WHERE (tsh.status LIKE :p23_status_sp OR tsh.status IS NULL)
    AND (tsh.machine_type LIKE :p23_machine_type_sp)
    AND ( tsh.machine_serial_number LIKE
    TO_CHAR (:p23_machine_serial_number_sp)
    OR tsh.machine_serial_number IS NULL
    AND ( TO_CHAR (tsh.failure_date, 'DD-MON-YY') LIKE
    TO_CHAR (:p23_failure_date_sp)
    OR TO_CHAR (tsh.failure_date, 'DD-MON-YY') IS NULL
    AND ( TO_CHAR (tsh.creation_date, 'DD-MON-YY')
    BETWEEN TO_CHAR (:p23_creation_date_sp)
    AND TO_CHAR (:p23_creation_date_sp1)
    OR TO_CHAR (tsh.creation_date, 'DD-MON-YY') IS NULL
    AND (tsh.issue_date LIKE :p23_date_of_issue_sp OR tsh.issue_date IS NULL)
    AND (tsh.country LIKE :p23_country_sp OR tsh.country IS NULL)
    AND ( tsh.local_report_number LIKE TO_CHAR (:p23_local_rep_num_sp)
    OR tsh.local_report_number IS NULL
    AND ( tsp.part_number LIKE TO_CHAR (:p23_part_number_sp)
    OR tsp.part_number IS NULL
    AND tsh.machine_type IN (
    SELECT DISTINCT machine_type
    FROM trx_sales_dept_machine_list
    WHERE sales_department_id IN (
    SELECT DISTINCT sales_department_id
    FROM trx_user_sales_department
    WHERE UPPER (user_name) =
    UPPER ('&APP_USER.'))
    AND SYSDATE >= valid_from)
    AND tsh.sr_header_id = tsp.sr_header_id
    can any one tell me wat is wroung in this query.
    Any other way to write this?
    Thank You,
    Amit

    Hi User....
    Here is some date range SQL that my teams uses with some success:
    For date columns that do not contain NULL values, try this (note the TRUNC, it might help with your "today" problem).
    The hard coded dates allow users to leave the FROM and TO dates blank and still get sensible results (ie a blank TO date field asks for all dates in the future.
    AND TRUNC(DATE_IN_DATABASE)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),:
    :P1_DATE_TO)
    For date columns that contain NULL values, try this (a little bit trickier):
    AND nvl(TRUNC(DATE_IN_DATABASE),
    decode( :P1_DATE_FROM,
    decode( :P1_DATE_TO,
    TO_DATE('30-DEC-3000'),
    NULL),
    NULL)
    BETWEEN
    decode( :P1_DATE_FROM,
    TO_DATE('01-JAN-1900'),
    :P1_DATE_FROM)
    AND
    decode( :P1_DATE_TO,
    TO_DATE('31-DEC-3000'),
    :P1_DATE_TO)
    Note the 30-DEC-3000 versus 31-DEC-3000. This trick returns the NULL dates when the FROM and TO date range items are both blank.
    I hope this helps.
    By the way, does anyone have a better way of doing this? The requirement is given a date column in a database and a FROM and a TO date item on a page,
    find all of the dates in the database between the FROM and TO dates. If the FROM date is blank, assume the user want all dates in the past (excluding NULL dates). If the TO date is blank, assume that the user wants all of the dates in the future (excluding NULL dates). If both FROM and TO dates are blank, return all of the dates in the databse (including NULL dates).
    Cheers,
    Patrick

  • Date range query

    I have the following query.
    I have a table that contains studentid,student_date_of_birthA second table contains studentid,class_passed,date_of_passingNow I want to know all students who passed their 'CLASS_X' during
    a particular date range and at the time of passing,the age of the student was 15 years.
    Any help would be greatly appreciated.
    Regards.

    Hi, this works in Oracle 9i
    SQL>SELECT studentid
    2 FROM table2
    3 JOIN table1
    4 USING (studentid)
    5 WHERE class_passed = 'CLASS_X'
    6 AND date_of_passing BETWEEN '&&Date1' AND '&&Date2'
    7 AND (FLOOR(MONTHS_BETWEEN('&Date1',student_date_of_birth)/12) = 15
    8 OR FLOOR(MONTHS_BETWEEN('&Date2',student_date_of_birth)/12) = 15)
    9 /
    Regards,
    Ely

  • Need suggestions on date range query

    I have a requirement to show the amount of product remaining. There is a table that holds updated "inventory" amounts with a date and tonnage, and a series of transactional tables that detail the individual disbursements from the stockpile. The trick is that the dates for the inventory adjustments may not all be the same, meaning that I need to individually resolve the stockpiles.
    This query will give me the inventory disbursements:
    select FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) as STATION,
      count(j.LOAD_JOB_ID) as LOADS,
               CASE SUM(w.SPOT_WEIGHT)
                 WHEN 0 THEN SUM(NVL(j.MAN_SPOT_WT,0))
                 ELSE SUM(w.SPOT_WEIGHT)
               END TONS
           from TC c, TC_LOAD_JOBS j, SPOT_WEIGHTS w
          where c.TC_ID = j.TC_ID
            and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
            and c.DATE_INDEX BETWEEN to_date('09/01/2009','MM/DD/YYYY') and sysdate
            and FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) in (810,410)
          group by FN_STN_KEY(j.FACTORY_ID, j.STATION_ID);Note that the date and the list of stations in the where clause are dynamic and selected by user. If this was only one station at a time it wouldn't be this complicated.
    This query will give me the last known inventory amount:
    select to_char(MAX(AS_OF_DT),'Mon DD, YYYY'), TONS
      from STATION_LOG
          where AS_OF_DT < sysdate and STN_KEY in (810,410) group by TONS;Again, the date and list of stations are selected by user. They should be identical to those selected for the other query.
    Does anyone have any good ideas on how to combine these two statements into a single report?
    Note: FN_STN_KEY acts as a join function. You don't really want me to get into why there isn't a single unique key to reference.

    Hi,
    I'm trying to follow your descrioption, but lots of things don't make sense to me.
    blarman74 wrote:
    Yeah. I put in some data so I could get the message back to you, then filled in the rest.
    So the user is going to pass in two parameters: The date of the report and the list of stations they want to get an inventory count on. What were the parameters that produced the output you posted before:
    STATION     INITIAL_TONS     USED_TONS     AS_OF_DATE
    810               835500        465100      09/01/2010
    410               495800        366900      09/02/2010
    550               568900        122600      08/31/2010
    What I need the report to do is
    1) take a station from the list
    2) find out the inventory tally from STATION_LOG where the date is the largest date less than the supplied date. This should give me AS_OF_DATE and my initial quantity.
    3) query the data table for all tons hauled from the AS_OF_DATE for that station.
    4) repeat for the next station.So this is what your existing PL/SQL code does. A non procedural language, like SQL, won't follow the same steps, of course.
    The sample data for station_log is:
    INSERT INTO STATION_LOG (1, to_date('08/31/2010','MM/DD/YYYY'), 810, 562500);
    INSERT INTO STATION_LOG (2, to_date('09/02/2010','MM/DD/YYYY'), 410, 495500);
    INSERT INTO STATION_LOG (3, to_date('09/01/2010','MM/DD/YYYY'), 910, 832600);
    INSERT INTO STATION_LOG (4, to_date('12/31/2010','MM/DD/YYYY'), 810, 239800);How do you get the initial_tons in the output above from the data above? Did you mean to post some new sample data for station_log?
    I still get ORA-00928 errors from all the INPUT statements.
    As I said, I can do it inside a loop in PL/SQL, but I got completely stumped on how I could accomplish this in SQL. The trick is that if I can do it in SQL, I can allow the user to export the data to csv using built-in functionality. If I have to do it in PL/SQL, I can't provide the export as easily.
    One more thing I just thought about, I am going to need to use a BETWEEN on the dates of the data I need to grab. I obviously don't want to grab data past another inventory tally record from STATION_LOG for the same station, and I can use an NVL so it cuts off at SYSDATE. I obviously haven't hauled anything in the future ;)I doubt if I'll get enough information to do this for you before I leave on vacation.
    Here's an example of what you need to do using the scott.emp table instead of your station_log table:
    SELECT       job
    ,       hiredate
    ,       sal
    FROM       scott.emp
    ORDER BY  job
    ,            hiredate
    JOB       HIREDATE           SAL
    ANALYST   03-Dec-1981       3000
    ANALYST   19-Apr-1987       3000
    CLERK     17-Dec-1980        800
    CLERK     03-Dec-1981        950
    CLERK     23-Jan-1982       1300
    CLERK     23-May-1987       1100
    MANAGER   02-Apr-1981       2975
    MANAGER   01-May-1981       2850
    MANAGER   09-Jun-1981       2450
    PRESIDENT 17-Nov-1981       5000
    SALESMAN  20-Feb-1981       1600
    SALESMAN  22-Feb-1981       1250
    SALESMAN  08-Sep-1981       1500
    SALESMAN  28-Sep-1981       1250Say we want to find, for each job in a given list, the sal that corresponds to the last hiredate that is no later than the given report_date. (This seems pretty close to what you heed: fior each stn_key in a given list, the quantity that corresponds to the last row that is no later than the given report_date.)
    That is, if we're only interested in the jobs CLERK, MANAGER and PRESIDENT, and only in hiredates on or before December 31, 1981, the output would be:
    JOB       LAST_HIREDA   LAST_SAL
    CLERK     03-Dec-1981        950
    MANAGER   09-Jun-1981       2450
    PRESIDENT 17-Nov-1981       5000That is, we want to ignore all jobs that are not in the given list, and all rows whose hiredate is after the given report_date. Among the rows that remain, we're interested only in the last one for each job.
    Note that the last_sal for CLERK is not 1300 or 1100: those values were after the given report_date. also, the last_sal for CLERK is not 800; that's not the last one of the remaining rows.
    Here's one way to get those results in pure SQL:
    DEFINE       jobs_wanted     = "CLERK,MANAGER,PRESIDENT"
    DEFINE       report_date     = "DATE '1981-12-31'"
    SELECT       job
    ,       MAX (hiredate)                         AS last_hiredate
    ,       MAX (sal) KEEP (DENSE_RANK LAST ORDER BY hiredate)     AS last_sal
    FROM       scott.emp
    WHERE       hiredate     <= &report_date
    AND        ',' || '&jobs_wanted' || ','     LIKE
           '%,' || job                  || ',%'
    GROUP BY  job
    ORDER BY  job
    ;I used substitution variables for the parameters. You could use bind_variables, or hard-code the values instead.
    The WHERE clause is applied before aggreate functions are computed, so rows after &report_date don't matter.
    "MAX (sal) KEEP (DENSE_RANK LAST ORDER BY hiredate)" means the sal that is associated with the last row, in order by hiredate. If there happens to be a tie (that is, two or more rows have exactly the same hiredate, and no row is later) then the highest sal from thsoe rows is returned; that's what MAX means here. Ties may be impossible in your data.
    You need to write a similar query using your station_log table, and join the results of that to your load_data table, including only the rows that have dates between the date in the sub-query (last_hiredate in my example) and the parameter report_date. That can be part of the join condition.

  • Query for date range? JE

    Hi,
    I have seem some posts on the JE forum regarding quering for date range, but it is mostly using DPL.
    Is there any way to do that using the JE API
    Thanks,
    Mohammad

    Hi Mohammad,
    A date range query can be performed as a key range query. There's nothing special about dates except that you'll want to use a key binding that gives a meaningful sort order. If you're representing your dates in milliseconds, then a LongBinding (in com.sleepycat.bind.tuple) will work well. In general, use tuple bindings for keys, because they provide a meaningful sort order.
    To perform a range query, this FAQ has some hints:
    http://www.oracle.com/technology/products/berkeley-db/faq/je_faq.html#28
    On range searches in general, they can be done with Cursor.getSearchKeyRange or with the SortedSet.subSet and SortedMap.subMap methods, depending on whether you are using the base API or the Collections API. It is up to you which to use.
    If you use Cursor.getSearchKeyRange you'll need to call getNext to iterate through the results. You'll have to watch for the end range yourself by checking the key returned by getNext. This API does not have a way to enforce range end values automatically.
    If you use the Collections API you can call subMap or subSet and get an Iterator on the resulting collection. That iterator will enforce both the beginning and the end of the range automatically.
    Does this answer your question?
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Date range sunday to monday

    Hello experts;
    I would like to design a date range query where the beginning of the week is always sunday and the end of the week is always monday. All help is appreciated.
    Thank you

    What do you mean by "design a date range"? And " beginning of the week is always sunday and the end of the week is always monday" doesn't make much sense. If it starts Sunday then last day of the week is Saturday. Anyway, nearest Sunday is:
    TRUNC(your_date_column + 1,'IW') - 1SY.

  • Date Ranges with EOMONTH

    Hi I'm look
    for a date ranges query, any help would be greatly appreciated<o:p></o:p>
    Ie
    01/06/2014 to 30/06/2014<o:p></o:p>
    SELECT
    count(DISTINCT[Form Number]) as OutofFunding
    FROM [dbo].[NEWVIEW]
    WHERE [Cohort Desc] IN ('Apprenticeships')
    AND [Expected End] > EOMONTH(GETDATE(), -1) <o:p></o:p>

    Here is how you can do datetime range with EOMONTH:
    SELECT Count(DISTINCT[form number]) AS OutofFunding
    FROM [dbo].[newview]
    WHERE [cohort desc] IN ( 'Apprenticeships' )
    AND [expected end] > Eomonth(Getdate(), -1)
    AND [expected end] < Dateadd(dd, 1, Eomonth(Getdate(), 4));
    BLOG on datetime ranges:
    http://www.sqlusa.com/bestpractices2008/between-dates/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • SQL Query on Date Range

    Hi, I am using Oracle 10g. I want a query which gives me below output.
    Data Setup
    ========
    create table t_date_range (
    ID     number (2),
    start_date     date,
    end_date     date);
    insert into t_date_range values (1,to_date('20110101', 'YYYYMMDD'),to_date('20110331', 'YYYYMMDD'));
    insert into t_date_range values (2,to_date('20110401', 'YYYYMMDD'),to_date('20110531', 'YYYYMMDD'));
    insert into t_date_range values (3,to_date('20110701', 'YYYYMMDD'),to_date('20110731', 'YYYYMMDD'));
    insert into t_date_range values (4,to_date('20110901', 'YYYYMMDD'),to_date('20111130', 'YYYYMMDD'));
    insert into t_date_range values (5,to_date('20111201', 'YYYYMMDD'),to_date('20111231', 'YYYYMMDD'));
    commit;
    SQL> select ID, to_char(start_date,'DD-MON-YYYY') START_DATE, to_char(end_date,'DD-MON-YYYY') END_DATE from t_date_range;
    ID START_DATE END_DATE
    1 01-JAN-2011 31-MAR-2011
    2 01-APR-2011 31-MAY-2011
    3 01-JUL-2011 31-JUL-2011
    4 01-SEP-2011 25-OCT-2011
    5 26-OCT-2011 30-NOV-2011
    6 01-DEC-2011 31-DEC-2011
    6 rows selected.
    I want result in this form:
    START_DATE END_DATE
    01-JAN-2011 31-MAY-2011
    01-JUL-2011 31-JUL-2011
    01-SEP-2011 31-DEC-2011
    Means if there is a difference of exact one day between "start_date of 2nd row" and "end_date of first row" then make a single row as shows in above results set.
    Thanks!

    Hi,
    Solomon Yakobson wrote:
    Keep in mind, Franks's solution assumes date ranges do not overlap. ...That's true. If rows can overlap, then we might need to use two sub-queries, like you did: one to see if a new group starts with this row, and another to count how many new groups have already started.
    The solution you posted assumes a relationship between id and dates. If we add a row like this to the sample data:
    insert into t_date_range values (6,to_date('20101201', 'YYYYMMDD'),to_date('20121231', 'YYYYMMDD'));that overlaps all the others, then how would that solution work?
    LAG won't work, because no matter how we sort the rows, we can't be sure that overlapping rows will be consecutive.
    Here's one way to handle overlapping rows:
    WITH     got_new_grp          AS
         SELECT     id, start_date, end_date
         ,     CASE
                  WHEN  start_date > 1 + MAX (end_date) OVER ( ORDER BY  start_date
                                                                        ,             id
                                                                        ROWS BETWEEN  UNBOUNDED PRECEDING
                                                  AND      1      PRECEDING
                  THEN  1
              END     AS new_grp
         FROM     t_date_range
    ,     got_grp          AS
         SELECT  start_date, end_date
         ,     COUNT (new_grp) OVER ( ORDER BY  start_date
                                     ,           id
                             ) AS grp
         FROM    got_new_grp
    SELECT       MIN (start_date)     AS start_date
    ,       MAX (end_date)     AS end_date
    FROM       got_grp
    GROUP BY  grp
    ORDER BY  start_date
    ;This solution uses id (assumed to be unique) just to get a consistent ordering, in case 2 (or more) rows have exactly the same start_date. It does not assume any relationship between ids and either start_date or end_date.
    I'm also assuming that start_date<=end_date on each row.
    Edited by: Frank Kulash on May 11, 2011 12:54 PM
    The above refers to the solution you oriognally posted, which was:
    with t1 as (
                select  id,
                        start_date,
                        end_date,
                        case
                          when lag(end_date) over(order by id) + 1 >= start_date then 0
                          else 1
                        end start_of_group
                  from  t_date_range
         t2 as (
                select  id,
                        start_date,
                        end_date,
                        sum(start_of_group) over(order by id) grp
                  from  t1
    select  min(start_date) start_date,
            max(end_date) end_date
      from  t2
      group by grp
      order by grp
    ;

  • Date range related query needed

    I have table 'ratemast' with following columns and data
    begindate      enddate           rate1
    01-12-2006      10-12-2006     750.00
    11-12-2006      25-12-2006     950.00
    26-12-2006      02-03-2007     1500.00
    the data in begindate and enddate may fall between any date range.
    it may be for a week or for a month or even more than that.
    i need a query to do the following:
    my query will have begindate and enddate for any date range which is not defined in a single row of ratemast.
    I need to pick indiviudal date and its respective rate and sum them and it should be divided by number of days.
    eg:- if begindate: 09-12-2006 enddate: 13-12-2006
    result should be : (750+750+950+950+950)/5
    Please help.

    Hi,
    Here's one way... you may have to alter it to check for count(*) = 0 or any other corner cases.
    [email protected](152)> create table ratemast(begindate date, enddate date, rate number);
    Table created.
    Elapsed: 00:00:00.22
    [email protected](152)> insert into ratemast(begindate, enddate, rate)
    values (date '2006-12-01', date '2006-12-10', 750);
    1 row created.
    Elapsed: 00:00:00.01
    [email protected](152)> insert into ratemast(begindate, enddate, rate)
    values (date '2006-12-11', date '2006-12-25', 950);
    1 row created.
    Elapsed: 00:00:00.00
    [email protected](152)> insert into ratemast(begindate, enddate, rate)
    values (date '2006-12-26', date '2007-03-02', 1500);
    1 row created.
    Elapsed: 00:00:00.00
    [email protected](152)> commit;
    Commit complete.
    Elapsed: 00:00:00.04
    [email protected](152)> select * from ratemast
      2  /
    BEGINDATE ENDDATE         RATE
    01-DEC-06 10-DEC-06        750
    11-DEC-06 25-DEC-06        950
    26-DEC-06 02-MAR-07       1500
    Elapsed: 00:00:00.03
    [email protected](152)> var begin_date varchar2(10);
    [email protected](152)> var end_date varchar2(10);
    [email protected](152)> exec :begin_date := '2006-12-09';
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    [email protected](152)> exec :end_date := '2006-12-13';
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    [email protected](152)> @ed
    Wrote file TEST.BRANDT_152_20070315150352.sql
      1  with dates as (
      2     select to_date(:begin_date, 'YYYY-MM-DD') + level - 1 as d
      3     from dual
      4     connect by level <= to_date(:end_date, 'YYYY-MM-DD') - to_date(:begin_date, 'YYYY-MM-DD') + 1
      5  )
      6  select dates.d
      7  , r.rate
      8  from dates
      9  , ratemast r
    10* where dates.d between r.begindate and r.enddate
    [email protected](152)> /
    D               RATE
    09-DEC-06        750
    10-DEC-06        750
    11-DEC-06        950
    12-DEC-06        950
    13-DEC-06        950
    Elapsed: 00:00:00.02
    [email protected](152)> ed
    Wrote file TEST.BRANDT_152_20070315150352.sql
      1  with dates as (
      2     select to_date(:begin_date, 'YYYY-MM-DD') + level - 1 as d
      3     from dual
      4     connect by level <= to_date(:end_date, 'YYYY-MM-DD') - to_date(:begin_date, 'YYYY-MM-DD') + 1
      5  )
      6  select :begin_date
      7  , :end_date
      8  , avg(r.rate) as fee
      9  from dates
    10  , ratemast r
    11  where dates.d between r.begindate and r.enddate
    12* group by :begin_date
    [email protected](152)> /
    :BEGIN_DATE                      :END_DATE                               FEE
    2006-12-09                       2006-12-13                              870
    Elapsed: 00:00:00.01
    [email protected](152)> exec :end_date := '2007-01-15';
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    [email protected](152)> @ed
    Wrote file TEST.BRANDT_152_20070315151840.sql
      1  with dates as (
      2     select to_date(:begin_date, 'YYYY-MM-DD') + level - 1 as d
      3     from dual
      4     connect by level <= to_date(:end_date, 'YYYY-MM-DD') - to_date(:begin_date, 'YYYY-MM-DD') + 1
      5  )
      6  select dates.d
      7  , r.rate
      8  from dates
      9  , ratemast r
    10* where dates.d between r.begindate and r.enddate
    [email protected](152)> /
    D               RATE
    09-DEC-06        750
    10-DEC-06        750
    11-DEC-06        950
    12-DEC-06        950
    13-DEC-06        950
    14-DEC-06        950
    15-DEC-06        950
    16-DEC-06        950
    17-DEC-06        950
    18-DEC-06        950
    19-DEC-06        950
    20-DEC-06        950
    21-DEC-06        950
    22-DEC-06        950
    23-DEC-06        950
    24-DEC-06        950
    25-DEC-06        950
    26-DEC-06       1500
    27-DEC-06       1500
    28-DEC-06       1500
    29-DEC-06       1500
    30-DEC-06       1500
    31-DEC-06       1500
    01-JAN-07       1500
    02-JAN-07       1500
    03-JAN-07       1500
    04-JAN-07       1500
    05-JAN-07       1500
    06-JAN-07       1500
    07-JAN-07       1500
    08-JAN-07       1500
    09-JAN-07       1500
    10-JAN-07       1500
    11-JAN-07       1500
    12-JAN-07       1500
    13-JAN-07       1500
    14-JAN-07       1500
    15-JAN-07       1500
    38 rows selected.
    Elapsed: 00:00:00.01
    [email protected](152)> ed
    Wrote file TEST.BRANDT_152_20070315150352.sql
      1  with dates as (
      2     select to_date(:begin_date, 'YYYY-MM-DD') + level - 1 as d
      3     from dual
      4     connect by level <= to_date(:end_date, 'YYYY-MM-DD') - to_date(:begin_date, 'YYYY-MM-DD') + 1
      5  )
      6  select :begin_date
      7  , :end_date
      8  , avg(r.rate) as fee
      9  from dates
    10  , ratemast r
    11  where dates.d between r.begindate and r.enddate
    12* group by :begin_date
    [email protected](152)> /
    :BEGIN_DATE                      :END_DATE                               FEE
    2006-12-09                       2007-01-15                       1243.42105
    Elapsed: 00:00:00.01
    [email protected](152)> cheers,
    Anthony

  • CUIC Hourly Interval Query Throughout Date Range (SQL Squirrel Stuff)

    I’m trying to create a specific report in CUIC using the "Contact Service Queue Activity Report by Interval” canned report.  The objective is to query intervals (by hour), throughout the whole reporting time frame.  This can be done by interval and reported per day in the canned report, but I’m trying to get the values per interval without the day displayed.  For example, I’d like a report that shows total calls per hour (8-9 am, 9-10, 10-11am etc) throughout the reporting date range. The report would look like this:
    Interval Start Time  Interval End Time     CSQ Name     Calls Presented    Handled
    8:00:00 AM     9:00:00 AM     CSQ_     41     40
    9:00:00 AM     10:00:00 AM     CSQ_     63     60
    10:00:00 AM     11:00:00 AM     CSQ_     50     50
    Instead of this:
    Interval Start Time  Interval End Time     CSQ Name     Calls Presented    Handled
    3/3/14 8:00     3/3/14 9:00     CSQ_     16     16
    3/3/14 9:00     3/3/14 10:00     CSQ_     23     21
    3/3/14 10:00     3/3/14 11:00     CSQ_     24     24
    3/4/14 8:00     3/4/14 9:00     CSQ_     13     13
    3/4/14 9:00     3/4/14 10:00     CSQ_     26     25
    3/4/14 10:00     3/4/14 11:00     CSQ_     14     14
    3/5/14 8:00     3/5/14 9:00     CSQ_     12     11
    3/5/14 9:00     3/5/14 10:00     CSQ_     14     14
    3/5/14 10:00     3/5/14 11:00     CSQ_     12     12

    Hi
    So you want the report to add up all the calls between 9-10am, e.g. if you run it for a week it would add up the calls for each day between 9 and 10 am and show a single total for that hour?
    Aaron

  • Count days in a month for a date range

    i am trying to find no. of days between 2 Date Ranges for a list of Ids. i used the logic in the below link:
    count days of the month
    My query is giving duplicates since, I have list of Ids.
    Doctor_ID     Patient_ID     ARRIVE_DT_TM     DISCH_DT_TM
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45
    763305     42972232     1/7/2013 20:27     3/15/2013 19:15
    25391509     42972298     2/4/2013 22:45     3/8/2013 22:03
    746779     42972331     1/4/2013 23:00     3/26/2013 21:50
    763305     42972338     3/4/2013 22:19     3/6/2013 19:35
    763305     42972411     11/4/2013 22:32     3/29/2013 17:30
    I am looking for query to give me for Patient_ID = 42972229
    MONTH     COUNT_DAYS
    201210     14
    201211     30
    201212     31
    201301     31
    201302     28
    201303     14
    I am running the following code and it loops through the months and gives duplicates when I remove where Patient_id IN (42972229)
    select
    Doctor_ID
    , Patient_ID
    , AR_DTTM
    , DSC_DTTM
    , TO_CHAR(ADD_MONTHS(TRUNC(date1, 'MONTH'), LEVEL - 1), 'YYYY MM') MONTHS_BET
    , (LEAST(date2, ADD_MONTHS(TRUNC(date1, 'MONTH') - 1, LEVEL)) - GREATEST(date1, ADD_MONTHS(TRUNC(date1, 'MONTH'), LEVEL - 1)))+ 1 AS DAYSCOUNT
    from (select
    Doctor_ID
    , Patient_ID
    , ARRIVE_DT_TM AR_DTTM
    , DISCH_DT_TM DSC_DTTM
    ,TRUNC(ARRIVE_DT_TM,'DDD') AS date1
    ,TRUNC(DISCH_DT_TM,'DDD') AS date2
    from temp where Patient_id IN (42972229)
    CONNECT BY LEVEL <= MONTHS_BETWEEN(TRUNC(date2, 'MONTH'), TRUNC(date1, 'MONTH')) + 1
    Please help!

    Hi,
    ASTRA_007 wrote:
    Results I would like to see are:
    Doctor_ID     Patient_ID     ARRIVE_DT_TM     DISCH_DT_TM     Month     CountofDays
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2012 10     14
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2012 11     30
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2012 12     31
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2013 01     31
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2013 02     28
    755722     42972229     10/18/2012 7:50     3/14/2013 20:45     2013 03     14
    763305     42972232     1/7/2013 20:27     3/15/2013 19:15     2013 01     25
    763305     42972232     1/7/2013 20:27     3/15/2013 19:15     2013 02     28
    763305     42972232     1/7/2013 20:27     3/15/2013 19:15     2013 03     15
    and so on...So each row represents a patient-month, and you want to display several columns from the temp table on each output row. In that case, include all those columns in both the SELECT and GROUP BY clauses, like this:
    WITH     universe     AS
         SELECT     *
         FROM     temp
    --     WHERE     patient_id     IN (42972229)
    ,     date_range     AS
         SELECT     TRUNC (MIN (arrive_dt_tm))     AS first_date
         ,     TRUNC (MAX (disch_dt_tm))     AS last_date
         FROM     universe
    ,     all_dates     AS
         SELECT     first_date + LEVEL - 1     AS a_date
         FROM     date_range
         CONNECT BY     LEVEL     <= (last_date + 1) - first_date
    SELECT    u.doctor_id
    ,       u.patient_id
    ,       u.arrive_dt_tm
    ,       u.disch_dt_tm
    ,       TO_CHAR ( TRUNC (a.a_date, 'MONTH')
                  , 'YYYY MM'
                )          AS month
    ,       COUNT (*)          AS count_days
    FROM       all_dates  a
    JOIN       universe   u  ON  a.a_date  BETWEEN  TRUNC (u.arrive_dt_tm)
                                         AND      u.disch_dt_tm
    GROUP BY  u.doctor_id
    ,       u.patient_id
    ,       u.arrive_dt_tm
    ,       u.disch_dt_tm
    ,         TRUNC (a.a_date, 'MONTH')
    ORDER BY  u.patient_id
    ,       TRUNC (a.a_date, 'MONTH')
    ;Output from your sample data (with no filtering):
    `DOCTOR_ID PATIENT_ID ARRIVE_DT_TM     DISCH_DT_TM      MONTH   COUNT_DAYS
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2012 10         14
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2012 11         30
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2012 12         31
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2013 01         31
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2013 02         28
        755722   42972229 10/18/2012 7:50  3/14/2013 20:45  2013 03         14
        763305   42972232 1/7/2013 20:27   3/15/2013 19:15  2013 01         25
        763305   42972232 1/7/2013 20:27   3/15/2013 19:15  2013 02         28
        763305   42972232 1/7/2013 20:27   3/15/2013 19:15  2013 03         15
      25391509   42972298 2/4/2013 22:45   3/8/2013 22:3    2013 02         25
      25391509   42972298 2/4/2013 22:45   3/8/2013 22:3    2013 03          8
        746779   42972331 1/4/2013 23:0    3/26/2013 21:50  2013 01         28
        746779   42972331 1/4/2013 23:0    3/26/2013 21:50  2013 02         28
        746779   42972331 1/4/2013 23:0    3/26/2013 21:50  2013 03         26
        763305   42972338 3/4/2013 22:19   3/6/2013 19:35   2013 03          3
    In the end the objective is to count the no. of days in each month between the arrival and discharge dates by Physician and for his/her patients.Then is the output above really what you want? Say you're interested in physician 763305. That physician had 18-patient days in March, 2013, but the output doesn't make it clear.
    I ran your query, it works great but I have a long list of patients for whom I have to run these counts.the query above includes all patient_ids.
    That's a separate problem, to be solved in the first sub-query, universe. The rest of the query will be unchanged.
    How will you know which patients to include? If you can derive the list from temp itself, just use a WHERE clause in universe. If you need to look at other tables, join them in universe, or use them in sub-queries in universe, or both.
    For exmple, if you decide that the list of patient_ids has no pattern, and that you'll need to store their ids in a separate table (perhaps a global temporary table), then universe might be:
    WITH     universe     AS
         SELECT     t.*     -- or list columns needed
         FROM     temp                        t
         JOIN     patient_ids_to_include  p 
                      ON  p.patient_id = t.patient_id
    ) ...The rest of the query can be the same as above.
    If a same patient is admitted again then Patient_ID will be different no matter when readmitted.Are you saying that patient_id identifies a visit, not a patient, and that the same person is assigned a different patient_id every time that person is admitted?
    For
    INSERT INTO temp (doctor_id, patient_id, arrive_dt_tm, disch_dt_tm)
    VALUES ( 755722
    , 42972229
    , TO_DATE ('03/14/2013 23:00', 'MM/DD/YYYY HH24:MI')
    , TO_DATE ('04/01/2013 12:00', 'MM/DD/YYYY HH24:MI')
    First the Patient ID will be different from the earlier admission. Second the results will show like:
    Doctor_ID     Patient_ID     ARRIVE_DT_TM     DISCH_DT_TM     Month     CountofDays
    755722     42972229     3/14/2013 23:00     4/1/2013 12:00     2012 03     14
    755722     42972229     3/14/2013 23:00     4/1/2013 12:00     2012 04     1Are you saying that temp.patient_id is unique, and so the situation is impossible?
    Edited by: Frank Kulash on May 7, 2013 10:23 AM

  • Visual Composer: Date Range in Query

    Hi,
    While working in Visual Composer, I have come across the need to re-use the same query 20 times, but with slightly different date ranges. One way would be to create 20 copies of the same query and change the selection dates as needed on each of them. However, is it possible to provide date ranges in a query in Visual Composer? Right now its only letting me enter single values.
    Thanks
    Adeel

    Problem can be resolved by using a colon between the dates. Furthermore, the DSTR function in the expression editor can be used to form the desired dates.

  • Query problem with date range

    I have a query that needs to pull data between a date range.
    I've tried several things and nothing seems to work.
    Any help would be greatly appreciated.
    Here's the code:
    <cftransaction>
    <cfquery name="QryFollowUp"
    datasource="NBProdReports">
    SELECT TblContractInfo_SubMenuTable.User_ID,
    TblContractInfo_SubMenuTable.Contract_Number,
    TblContractInfo_SubMenuTable.Transaction_Type,
    TblContractInfo_SubMenuTable.Notes,
    TblContractInfo_SubMenuTable.Num_Checks_Trans,
    TblMasterTrans.Date_Opened
    from TblContractInfo_SubMenuTable ,tblMasterTrans
    WHERE Transaction_Type = 'FollowUp'
    And TblContractInfo_SubMenuTable.Task_Number =
    tblMasterTrans.Task_Number
    And TblMasterTrans.Date_Opened BETWEEN #form.StartDate# AND
    #form.EndDate#
    ORDER BY TblMasterTrans.Date_Opened ASC,
    TblContractInfo_SubMenuTable.User_id ASC
    </cfquery>
    </cftransaction>

    Any help would be greatly appreciated.
    Ok, why are you using a <cftransaction...> around a
    single select query?
    It should be unnecessary.
    This is probably not helpful to your original question. There
    is
    nothing obviously wrong with your query at least to my glance
    through.
    Thus this important question, the one without which you are
    unlikely to
    get any helpful advice, "How does this not work?" Error
    Messages? No
    Data? Wrong Data? Serves you coffee instead of tea?
    It would also probably be helpful to know how your date data
    is
    represented in the database and the form controls, depending
    on what
    your difficulties are.

Maybe you are looking for

  • Sublist by using ALV OO can not be refreshed

    Hi Gurus, i met with a very strange problem. i created a interactive list by using ALV OO and if you double click on one of the rows, the screen will go to a sublist which displays the detail information of the row. My question is every time i chose

  • Help! "Disk can not be read from or written to" error

    Hi, I just bought a couple of movies on itunes but when I try to sync them to iphone it stalls and I get the error "Attempt to copy to disk "my iphone" failed. The disk could not be read from or written to". Oddly though everything else except the vi

  • Can't get second drive to mount when starting up using OS 9.2.2.

    I'm running a 400 MHz Sawtooth (800 meg ram) with a 20 gig master drive and 80 gig slave I recently installed. All is working fine when running in OS 10.4.3. I partitioned the slave drive and want to run VPC 4.0 in a OS 9.04 environment. I understand

  • Drop shadow on text in table

    Is there any way to give text in a teable a drop shadow without giving the stroke of the table a drop shadow?

  • Inspection plan BDC reg

    Hello friends, We have writting one BDC for creating and changing the inspection plan, In this, the plan creation is successfully done. when we go for change, the system throws the error "task list is invalid create task list". once we log out the se