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
;

Similar Messages

  • SQL Query with Date Range

    I have a query that will retrieve order between selected dates. It works great but returns no record if the 2 dates are the same.
    Example:
    Orders between 9-1-2010 and 9-30-2010 retunes 35 records.
    But if I select between -9-25-2010 and 9-25-2010, so I can see all order from this 1 day, it returns 1 records, and I know there are records for that day!
    Here's my query:
    <%
    Dim rsOrders__MMColParam
    rsOrders__MMColParam = "1"
    If (Request.QueryString("datefrom") <> "") Then
      rsOrders__MMColParam = Request.QueryString("datefrom")
    End If
    %>
    <%
    Dim rsOrders__MMColParam2
    rsOrders__MMColParam2 = "1"
    If (Request.QueryString("dateto") <> "") Then
      rsOrders__MMColParam2 = Request.QueryString("dateto")
    End If
    %>
    <%
    Dim rsOrders
    Dim rsOrders_cmd
    Dim rsOrders_numRows
    Set rsOrders_cmd = Server.CreateObject ("ADODB.Command")
    rsOrders_cmd.ActiveConnection = MM_ezcaldatasource_STRING
    rsOrders_cmd.CommandText = "SELECT * FROM dbo.orders WHERE (OrderDate between ? and ?) AND Finalized  = 1"
    rsOrders_cmd.Prepared = true
    rsOrders_cmd.Parameters.Append rsOrders_cmd.CreateParameter("param1", 135, 1, -1, rsOrders__MMColParam) ' adDBTimeStamp
    rsOrders_cmd.Parameters.Append rsOrders_cmd.CreateParameter("param2", 135, 1, -1, rsOrders__MMColParam2) ' adDBTimeStamp
    Set rsOrders = rsOrders_cmd.Execute
    rsOrders_numRows = 0
    %>

    2 possible
    1) Change the column's data type from a datetime to a date if supported by your DBMS
    2) Use date math to always add 1 day to the end date. So instead of the end date of 9-25-2010 (00:00) it will be 9-26-2010 (00:00)

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • Multiple SQL Query as Data Source

    I have an SQL Query as Data Source of my Crystal Report. It combine the contents of two tables.
    I want to do another SQL query based on the previuos SQL Query.
    Can I do this in CR ? How I can reference the new SQL query to the main SQL query ?
    Thanks,
    Gabriel

    This is my main Query
    SELECT
    SBO_001.dbo.JDT1.Account,
    sum(SBO_001.dbo.JDT1.SYSDeb - SBO_001.dbo.JDT1.SYSCred) AS Balance_001,
    0 as Balance_004
    FROM SBO_001.dbo.JDT1
    GROUP BY SBO_001.dbo.JDT1.Account
    UNION
    SELECT
    SBO_004.dbo.JDT1.Account,
    0 as Balance_001,
    sum(SBO_004.dbo.JDT1.SYSDeb - SBO_004.dbo.JDT1.SYSCred) AS Balance_004
    FROM SBO_004.dbo.JDT1
    GROUP BY SBO_004.dbo.JDT1.Account
    This is a result
    Account     Balance_001     Balance_004
    80800005     0     -431.67
    80800005     590121.07           0
    80800006     -3621028.250            0     
    88780056     5000.00                    0
    90731001     0                          174780.11     
    I want to obtain this result
    Account     Balance_001            Balance_004
    80800005     590121.07             -431.67
    80800006     -3621028.250            0     
    88780056     5000.00                    0
    90731001     0                          174780.11     
    How I Can modify this Query?
    Thanks,
    Edited by: gablus on Aug 7, 2009 1:43 AM

  • Querying on date range issue?

    Hi,
    I'm looking for a solution for this issue,
    In the DB Table there is a column of type TIMESTAMP. so when i query for date range using BETWEEN keyword it returns data inserted on next day at 12.00.00 AM
    example :
    Table A
    ColumnA_
    data1
    data2
    data3
    ColumnTime_
    08/03/2010 11.55.00 AM
    08/04/2010 12.00.00 AM
    08/04/2010 12.00.01 AM
    here when I query using between (08/03/2010 and 08/04/2010) keyword on Column_Time then ,
    Ouput
    data1
    data2
    but I'm just looking for data1 in the output, any ideas?

    Between is inclusive of both boundaries:
    column between condition1 and condition2Translates into
    condition1 >= column
    and
    condition2 <= columnSo tell the code what you want ... in your case
    condition1 >= column
    and
    condition2 < columnI'm not sure if you expect the >= or not...adjust as needed.

  • 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

  • SQL Query with variable range

    Hi
      I want to give range to a user to enter in a variable through sql query . If there are 200 records , if user wants to display from 5-45 , 75-110 , 130-145. how it can be done through SQl Query
    Thanks
    Edited by: Matt on Aug 31, 2010 6:23 PM - modified title - please use a meaningful title in future

    Dear Saini,
    This query will allow you to choose the values only when you know them.
    SELECT T0.[DocEntry], T0.[ItemCode] FROM INV1 T0 WHERE T0.[LineNum] >[%0]   and T0.[LineNum] <[%1]
    If you run it in the query Generator in SAP Business One a little window will pop up and will ask you to choose the 2 variables.
    You can choose different variables every time you run it. At least you won't have to save many queries with different values.
    If you want 2 different groups, e.g. from 10 to 20 and from 30 to 40, then you can add another part in the where clause:
    SELECT T0.[LineNum], T0.[ItemCode], T0.[DocEntry] FROM INV1 T0 WHERE T0.[LineNum]  >= [%0] and  T0.[LineNum]  <= [%2] and T0.[LineNum]  >= [%4] or  T0.[LineNum]  <= [%6]
    Please, let me know if this query helps.
    Regards,
    Marcella Rivi
    SAP Business One Forums Team

  • Report from sql query invalid date condition

    Hi, I created a Reports From SQL Query. My sql is like
    "select column1, column2
    from myschema.tablename
    where mydate > :p_date1 and mydate < :p_date2"
    I am using portal with turkish and english option. If I pass p_date paramaters 'dd-MON-yyyy' format
    (for example p_date1 = 23-MAR-2003 p_date2 = 26-APR-2003) in english mode portlet is return correct result,
    in turkish mode 'No Row Returned'. I changed my sql statement with
    "select column1, column2
    from myschema.tablename
    where to_date(mydate,'dd/mm/yyy') > to_date(:p_date1,'dd/mm/yyy') and to_date(mydate) < to_date(:p_date2,'dd/mm/yyyy')"
    and I pass p_date parameters 'dd/mm/yyyy' format (for example p_date1 = 23/03/2003 p_date2 = 26/04/2003)
    but now turkish and english mode No row returned.
    How may I write correct sql statament. My database NLS_DATE_FORMAT=DD/MM/YYYY and NLS_LANGUAGE=TURKISH.
    thanks.

    Hi,
    Try this for turkish mode:
    Case 1: the 'mydate' column has a kind of a char data type (like char, varchar or varchar2)
    and a value like '30/03/2003'
    "select column1, column2
    from myschema.tablename
    where
    to_date(mydate,'DD/MM/YYYY') > :p_date1
    and
    to_date(mydate,'DD/MM/YYYY') < :p_date2"
    Case 2: the mydate column has a date type:
    "select column1, column2
    from myschema.tablename
    where
    mydate > :p_date1
    and
    mydate < :p_date2"
    In both cases use the following parameter values:
    p_date1 = 23/03/2003
    p_date2 = 26/04/2003
    This should work
    Thanks
    Peter

  • SQL query generating data in SQL management studio but not in CUIC interface

    Hello,
    I'm working on a UCCE 9.0 system
    I created SQL query for a  report.
    Whenever I run the query inside the SQL management studio, it works and generates data, but when I run it in the CUIC interface it works but generates nothing. As you can see in the below snapshot, it contains 209 records that are not being displayed.
    Any help would be greatly apprciated

    Is it a custom report ? Can you right click on your Custom Report and click on Edit Views. You need to check whether you have Grid Headers Listed.
    Regards,
    Senthil

  • PL/SQL function body return sql query, no data found problem

    Hi all,
    we are trying to build a dynamic report based on item selection by user. we are using SQL Query (PL/SQL function body returning SQL query). However when a user change the item and submit the page . The following error appears.
    ORA-01403: no data found.
    our query is so simple
    declare
    l_query varchar2(30000) default 'select id from chw';
    begin
    if(:P11_PARA=1) then
    l_query:='select name from chw';
    end if;
    return l_query;
    end;
    any quick help please.

    Hello Mike,
    I tried it, the problem still exists.
    ORA-01403: no data found
    my new code is
    declare
    l_query varchar2(30000) default 'select id from chw';
    begin
    if (nvl(TO_NUMBER(:P11_PARA),0) = 1) then
    l_query:='select name from chw';
    end if;
    return (l_query);
    end;
    note, there is no process in this page.
    Edited by: M.Jabr on Oct 14, 2009 6:13 AM

  • SQL Query using DATS data type

    Hello people,
    I have a table 'TableA' with a column 'xpto' that has DATS data type.
    A lot of lines in this table has this field empty.
    I have to create a SQL query to select those lines with this field not empty.
    Select * from TableA
    where xpto is not null
    It does not work.... The result is all the lines in the table.
    What is wrong?
    Thanks!

    Easiest way to do this is :
    constants l_xpto   type tableA-xpto  value is initial
    Select * from TableA
    where xpto ne l_xpto.
    You can see the NULL/NOT NULL settings for the column through SE11
    Utilities -> Database Object -> Display.
    I tend to set the "Initial Value" flag when adding columns to tables, which creates the database column as NOT NULL with a default value (whatever SAP considers the initial value for that datatype). I think SAP does this by default, but I've had issues where it hasn't so I do this to ensure consistency
    Chris Bain

  • Problem with a SQL query involving dates

    I have a database with each task made by a developer in the company's systems, with 2 fields to determine the duration of the tasks: begin_date and end_date, both Dates. Now I have to make an SQL query returning the total of hours each one worked counting every task, so I'm using something like this (simplifying):
    select user_id, sum(end_date - begin_date)
    from task
    group by user_id
    but I get a weird fractional number. How do I do this query?

    What database are you using? Oracle?
    The weird fractional number is probably the difference between the dates in days. If you want it in hours, try multiplying it with 24.
    select user_id, sum(end_date - begin_date) * 24
    from task
    group by user_id

  • T-SQL Query Duplicate dates.

    A table is called ‘ImportEvents’ There are currently 50 records in this table.  The user has the ability to enter the ‘Import Date’ manually and multiple imports could have happened on the same date.  What SQL query would you use to identify
    a list of all the dates on which an upload has occured without duplicates?

    If I want the number of Imported dates that don't have duplicate values how could I aggregate the query ?
    In sumo -
    50 records say 18 records where created on one date and 32 on 32 different dates how can I retrieve the list of 33 records based on the Imported Date.
    DECLARE @ImportEvents TABLE (importDate date)
    INSERT INTO @ImportEvents (importDate)
    VALUES ('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),('2014-01-01'),
    ('2014-01-02'),('2014-01-03'),('2014-01-04'),('2014-01-05'),('2014-01-06'),
    ('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07'),('2014-01-07')
    select importDate
    From @ImportEvents
    group by importDate
    having sum(importDate) = 1
    Thanks
    Richard

  • Setting Default value with SQL Query as Data Model

    Hi All,
    I am developing report based on SQL query.date set as 'SQL Query'. I have created two params start-date and end-date. I am fetching records from database between these two dates.
    I want to populate sysdate as a default values. I do not want to use datatemplate approach i mean using beforeReport trigger.
    Thansk,
    Vara

    Hi Vara,
    To set the default value for one of your parameters to SYSDATE you need to enter:
    {$SYSDATE()$}
    in the Default Value text box
    Is this what you require?
    Cheers
    Andy

  • How to display the SQL query's date parameters to the report

    Hi all,
    I'd like to take the date parameters that are contained in my query and have them appear on the report and/or have the sysdate appear on the report. Any ideas on how to do this? Thanks!

    Hi..
    To display parameters which are part of SQl Query in the output..
    http://blogs.oracle.com/xmlpublisher/2008/07/where_are_the_parameter_values.html
    HTH..

Maybe you are looking for