Date range SQL

I have a 2 tables table like this:
Employee Table
emp_id  region  active_date
A100    01      8/19/2009
A100    01      8/21/2009
A100    01      8/27/2009
A100    01      9/2/2009
A100    01      10/1/2009
A100    01      3/27/2010
Date_Lkp Table
Date_sk     Start_dt     End_date     
1     7/15/2009     8/14/2009
2     8/15/2009     9/14/2009
3     9/15/2009     10/14/2009
4     10/15/2009     11/14/2009
5     11/15/2009     12/14/2009
6     12/15/2009     1/14/2010
7     1/15/2010     2/14/2010
8     2/15/2010     3/14/2010
9     3/15/2010     4/14/2010I need an ouput like this:
emp_id  region  Start_dt     End_date     Date_sk
A100    01      8/19/2009     9/14/2009     2
A100    01      9/15/2009     10/14/2009     3
A100    01      3/15/2010     4/14/2010     9Records with SK 1,4-8 are not there because we dont have the employee active during that time. Also pls note that start date of the 1st record in output is same as the employee's Active start date.
Thanks.
Edited by: user572405 on Dec 1, 2010 1:28 PM

So you want Active_Date be selected as the start date for all records ?
select empid, region,  case when c > 1 then min(active_date)
                                else min(start_dt) end as start_dt,
                                end_dt, date_sk
from (                               
select empid, region,  start_dt, end_dt, date_sk, active_date, count(date_sk) over (partition by empid, region, start_dt, end_dt) c
from (
         select 'A100' empid,    '01' region,      to_date('8/19/2009', 'MM/DD/RRRR') active_date from dual union all
         select 'A100',    '01',      to_date('8/21/2009', 'MM/DD/RRRR') from dual union all
         select 'A100',    '01',      to_date('8/27/2009', 'MM/DD/RRRR') from dual union all
         select 'A100',    '01',      to_date('9/2/2009', 'MM/DD/RRRR') from dual union all
         select 'A100',    '01',      to_date('10/1/2009', 'MM/DD/RRRR') from dual union all
         select 'A100',    '01',      to_date('3/27/2010', 'MM/DD/RRRR') from dual
) m,
        select 1 date_sk,    to_date('7/15/2009', 'MM/DD/RRRR') start_dt,    to_date('8/14/2009', 'MM/DD/RRRR') end_dt from dual union all
        select 2,    to_date('8/15/2009', 'MM/DD/RRRR'),    to_date('9/14/2009', 'MM/DD/RRRR') from dual union all
        select 3,    to_date('9/15/2009', 'MM/DD/RRRR'),    to_date('10/14/2009', 'MM/DD/RRRR') from dual union all
        select 4,    to_date('10/15/2009', 'MM/DD/RRRR'),    to_date('11/14/2009', 'MM/DD/RRRR') from dual union all
        select 5,    to_date('11/15/2009', 'MM/DD/RRRR'),       to_date('12/14/2009', 'MM/DD/RRRR') from dual union all
        select 6,    to_date('12/15/2009', 'MM/DD/RRRR'),       to_date('1/14/2010', 'MM/DD/RRRR') from dual union all
        select 7,    to_date('1/15/2010',  'MM/DD/RRRR'),    to_date('2/14/2010', 'MM/DD/RRRR') from dual union all
        select 8,    to_date('2/15/2010',  'MM/DD/RRRR'),      to_date('3/14/2010', 'MM/DD/RRRR') from dual union all
        select 9,    to_date('3/15/2010',  'MM/DD/RRRR'),      to_date('4/14/2010', 'MM/DD/RRRR') from dual
) d
where active_date between start_dt and end_dt
group by empid, region,  end_dt, date_sk, c
order by 3And the result is:
DATE_SK REGION  START_DT    END_DT      DATE_SK
A100        01  8/19/2009   9/14/2009       2
A100        01  9/15/2009   10/14/2009      3
A100        01  3/15/2010   4/14/2010       9Edited by: Zaafran Ahmed on Dec 1, 2010 4:04 PM

Similar Messages

  • 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

  • Scan Date Range SQL

    User requested to find all current terminated employee who was eligible for benefit in 2008.
    We need to fetch data from Oracle Application HR Date Tracked table, PER_ALL_ASSIGNEMNTS_F which employee’s assignment record is stored based on the EFFECTIVE_START and EFFECITVE_END dates.
    It's possible an employee who was eligible for benefit in MAR-MAY but became ineligible in JUN-JULY. (That would be 2 assignment records with different range of effective start and end date).
    We've developed a PL/SQL for scanning the assignment record day by day thru out 2008. See the code below.
    The question is, how can we implement same logic (scanning the assignment record day by day) in PL/SQL into SQL?
    Thanks!
    (seems like this is different forum found in metalink, I'm sorry if I posted twice.)
    ============================================================
    (FETCHING TERMINATED EEs)
    for i_counter in 0 .. (to_date('01/01/2008','mm/dd/yyyy')to_date('12/31/2008','mm/dd/yyyy')) loop
    check_date := to_date('01/01/2008','mm/dd/yyyy')+i_counter;
    --Validate if the assignment is eligible for benefit by using genterated check_date.
    v_found :=0;
    select 1
    into v_found
    from per_all_assignments_f
    where check_date between effective_start_date and effective_end_date
    and group_id = 137 --eligible for benefit
    if v_found = 1 then
    v_eligible_found := 'YES';
    exit;
    end if;
    end loop;
    Edited by: user595907 on Mar 23, 2009 5:10 PM
    Edited by: user595907 on Mar 23, 2009 5:11 PM

    Frank Kulash wrote:
    I'm glad it helped, but I still don't understand exactly what you need.
    Do you want 366 rows of output?
    If so, then yes, this is a good way to get it.
    If not, there's probably a better way, as Sy suggested.
    Hi Frank
    The assignment record we have is date tracked which means each record is tracked by effective_start and effective_end.
    An employee could have mutiple assignment record within an year.
    User is asking to report any ee who is currently terminated and who was eligible for benefit (a data column in assignment record) anytime in 2008.
    The idea I had came from the PL/SQL logic.
    By using PL/SQL, I can scan the assignment record day by day. That helped to fetch every assignment record where the check_date falls between the effective_start and effective_end.
    Also, reason I asked to use the "CONNECT BY Query" (thanks Frank!) because not all assignment starts and ends between 1/1/2008 and 12/31/2008.
    Some ee could have started prior to 2008 and ended mid 2008 and then started the end of 2008.
    Please let me know if there is a better way to resolve this problem.
    Thanks everyone for all the ideas, I really appreciate it!
    Brian.

  • Tuning date range SQL

    I have a DATA table which consists of Minutely data. For every unique filename, solar_id, year, day there is a unique processing stage that can exist and to find the highest processing stage we select the MAX(date_stamp) for that particular day since it will be the latest touched stage.
    So for any given day we can have 1440minutes x (5processing stages on average) = ~7k records.
    If I have a query that wants to look at the highest processing stage that exists each day over a TIME FRAME, how can I improve it's performance?
    SELECT DISTINCT s.NAME NAME, s.climate_id climate_id, a.solar_id solar_id,
                    a.processing_stage processing_stage, a.YEAR YEAR, a.DAY DAY,
                    TO_CHAR (a.date_stamp, 'YYYY-MM-DD HH24:MI:SS') date_stamp, a.user_id
               FROM solar_station s, DATA a
              WHERE a.solar_id = '636'
                AND s.solar_id = '636'
                AND s.climate_id = '611KBE0'
                AND a.solar_id = s.solar_id
                AND a.time_stamp BETWEEN TO_DATE ('2004-9-8', 'YYYY-MM-DD')
                                     AND TO_DATE ('2004-9-20', 'YYYY-MM-DD')
                AND (a.solar_id, a.filename, a.YEAR, a.DAY, a.date_stamp) IN (
                       SELECT b.solar_id, b.filename, b.YEAR, b.DAY, MAX (b.date_stamp)
                           FROM DATA b
                          WHERE b.solar_id = '636'
                            AND b.solar_id = s.solar_id
                            AND b.time_stamp BETWEEN TO_DATE ('2004-9-8', 'YYYY-MM-DD')
                                                 AND TO_DATE ('2004-9-20', 'YYYY-MM-DD')
                       GROUP BY b.solar_id, b.filename, b.YEAR, b.DAY)
           ORDER BY s.NAME, a.YEAR, a.DAY;The data table is partioned by YEAR and sub-partioned by solar_id.

    Hmm, still a full table scan on data. This is
    probably caused by the unnecessary line
    AND b.solar_id = s.solar_idWhat happens if you remove this line?
    Regards,
    Rob.
    SELECT DISTINCT s.NAME NAME, s.climate_id climate_id, a.solar_id solar_id,
                    a.processing_stage processing_stage, a.YEAR YEAR, a.DAY DAY,
                    TO_CHAR (a.date_stamp, 'YYYY-MM-DD HH24:MI:SS') date_stamp, a.user_id
               FROM solar_station s, DATA a
              WHERE a.solar_id = '636'
                AND s.solar_id = '636'
                AND s.climate_id = '611KBE0'
                --AND a.solar_id = s.solar_id
                and year between 2004 and 2004
                AND a.time_stamp BETWEEN TO_DATE ('2004-9-8', 'YYYY-MM-DD')
                                     AND TO_DATE ('2004-12-20', 'YYYY-MM-DD')
                AND (a.solar_id, a.filename, a.YEAR, a.DAY, a.date_stamp) IN (
                       SELECT   b.solar_id, b.filename, b.YEAR, b.DAY, MAX (b.date_stamp)
                           FROM DATA b
                          WHERE b.solar_id = '636'
                            --AND b.solar_id = s.solar_id
                            and year between 2004 and 2004
                            AND b.time_stamp BETWEEN TO_DATE ('2004-9-8', 'YYYY-MM-DD')
                                                 AND TO_DATE ('2004-12-20', 'YYYY-MM-DD')
                       GROUP BY b.solar_id, b.filename, b.YEAR, b.DAY)
           ORDER BY s.NAME, a.YEAR, a.DAY;
    PLAN_TABLE_OUTPUT
    Plan hash value: 4121458178
    | Id  | Operation                       | Name             | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                |                  |   156 | 19500 | 30539   (4)| 00:06:07 |       |       |
    |   1 |  SORT ORDER BY                  |                  |   156 | 19500 | 30539   (4)| 00:06:07 |       |       |
    |   2 |   HASH UNIQUE                   |                  |   156 | 19500 | 30538   (4)| 00:06:07 |       |       |
    |*  3 |    HASH JOIN                    |                  |   156 | 19500 | 30537   (4)| 00:06:07 |       |       |
    |   4 |     NESTED LOOPS                |                  |  1401 | 95268 | 15279   (4)| 00:03:04 |       |       |
    |*  5 |      TABLE ACCESS BY INDEX ROWID| SOLAR_STATION    |     1 |    27 |     1   (0)| 00:00:01 |       |       |
    |*  6 |       INDEX UNIQUE SCAN         | SOLAR_STATION_PK |     1 |       |     0   (0)| 00:00:01 |       |       |
    |   7 |      VIEW                       | VW_NSO_1         |  1401 | 57441 | 15278   (4)| 00:03:04 |       |       |
    |   8 |       SORT GROUP BY             |                  |  1401 | 82659 | 15278   (4)| 00:03:04 |       |       |
    |   9 |        PARTITION RANGE ITERATOR |                  |   272K|    15M| 15245   (3)| 00:03:03 |    10 |    11 |
    |  10 |         PARTITION HASH SINGLE   |                  |   272K|    15M| 15245   (3)| 00:03:03 |     1 |     1 |
    |* 11 |          TABLE ACCESS FULL      | DATA             |   272K|    15M| 15245   (3)| 00:03:03 |       |       |
    |  12 |     PARTITION RANGE ITERATOR    |                  |   272K|    14M| 15254   (4)| 00:03:04 |    10 |    11 |
    |  13 |      PARTITION HASH SINGLE      |                  |   272K|    14M| 15254   (4)| 00:03:04 |     1 |     1 |
    |* 14 |       TABLE ACCESS FULL         | DATA             |   272K|    14M| 15254   (4)| 00:03:04 |       |       |
    Predicate Information (identified by operation id):
       3 - access("A"."SOLAR_ID"="$nso_col_1" AND "A"."FILENAME"="$nso_col_2" AND "A"."YEAR"="$nso_col_3" AND
                  "A"."DAY"="$nso_col_4" AND "A"."DATE_STAMP"="$nso_col_5")
       5 - filter("S"."CLIMATE_ID"='611KBE0')
       6 - access("S"."SOLAR_ID"='636')
      11 - filter("B"."TIME_STAMP">=TO_DATE('2004-09-08 00:00:00', 'yyyy-mm-dd hh24:mi:ss') AND "YEAR"=2004 AND
                  "B"."SOLAR_ID"='636' AND "B"."TIME_STAMP"<=TO_DATE('2004-12-20 00:00:00', 'yyyy-mm-dd hh24:mi:ss'))
      14 - filter("A"."TIME_STAMP">=TO_DATE('2004-09-08 00:00:00', 'yyyy-mm-dd hh24:mi:ss') AND "YEAR"=2004 AND
                  "A"."SOLAR_ID"='636' AND "A"."TIME_STAMP"<=TO_DATE('2004-12-20 00:00:00', 'yyyy-mm-dd hh24:mi:ss'))>
    Message was edited by:
    Rob van Wijk
    ddition questions:
    What is the outcome of:
    select count(*)
    from ( SELECT s.NAME NAME
    , s.climate_id climate_id
    , a.solar_id solar_id
    , a.processing_stage processing_stage
    , a.YEAR YEAR
    , a.DAY DAY
    , TO_CHAR (a.date_stamp, 'YYYY-MM-DD HH24:MI:SS')
    date_stamp
    , a.user_id
    , max(a.date_stamp) over (partition by a.solar_id,
    a.file_name, a.year, a.day) max_date_stamp
    FROM solar_station s
    , DATA a
    WHERE a.solar_id = '636'
    AND s.solar_id = '636'
    AND s.climate_id = '611KBE0'
    AND a.solar_id = s.solar_id
    AND year between 2004 and 2004
    AND a.time_stamp BETWEEN TO_DATE ('2004-9-8',
    'YYYY-MM-DD') AND TO_DATE ('2004-12-20',
    'YYYY-MM-DD')
    Here we get:
    COUNT(*)
    1266111
    1 row selected.
    You might remove the subquery by issuing:
    select distinct *
    from ( SELECT s.NAME NAME
    , s.climate_id climate_id
    , a.solar_id solar_id
    , a.processing_stage processing_stage
    , a.YEAR YEAR
    , a.DAY DAY
    , TO_CHAR (a.date_stamp, 'YYYY-MM-DD HH24:MI:SS')
    date_stamp
    , a.user_id
    , max(a.date_stamp) over (partition by a.solar_id,
    a.file_name, a.year, a.day) max_date_stamp
    FROM solar_station s
    , DATA a
    WHERE a.solar_id = '636'
    AND s.solar_id = '636'
    AND s.climate_id = '611KBE0'
    AND a.solar_id = s.solar_id
    AND year between 2004 and 2004
    AND a.time_stamp BETWEEN TO_DATE ('2004-9-8',
    'YYYY-MM-DD') AND TO_DATE ('2004-12-20',
    'YYYY-MM-DD')
    date_stamp = max_date_stamp
    ORDER BY s.NAME
    , a.YEAR
    , a.DAY
    select distinct *
      from ( SELECT s.NAME NAME
                  , s.climate_id climate_id
                  , a.solar_id solar_id
                  , a.processing_stage processing_stage
                  , a.YEAR YEAR
                  , a.DAY DAY
                  , TO_CHAR (a.date_stamp, 'YYYY-MM-DD HH24:MI:SS') date_stamp
                  , a.user_id
                  , max(a.date_stamp) over (partition by a.solar_id, a.filename, a.year, a.day) max_date_stamp
               FROM solar_station s
                  , DATA a
              WHERE a.solar_id = '636'
                AND s.solar_id = '636'
                AND s.climate_id = '611KBE0'
                AND a.solar_id = s.solar_id
                AND year between 2004 and 2004
                AND a.time_stamp BETWEEN TO_DATE ('2004-9-8', 'YYYY-MM-DD') AND TO_DATE ('2004-12-20', 'YYYY-MM-DD')
    where date_stamp = max_date_stamp
    ORDER BY NAME
         , YEAR
         , DAY;
    PLAN_TABLE_OUTPUT
    Plan hash value: 3043498213
    | Id  | Operation                       | Name             | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT                |                  | 14702 |   990K|       | 20550   (3)| 00:04:07 |       |       |
    |   1 |  SORT UNIQUE                    |                  | 14702 |   990K|  9608K| 19862   (3)| 00:03:59 |       |       |
    |*  2 |   VIEW                          |                  | 90794 |  6117K|       | 18372   (3)| 00:03:41 |       |       |
    |   3 |    WINDOW SORT                  |                  | 90794 |    13M|    33M| 18372   (3)| 00:03:41 |       |       |
    |*  4 |     HASH JOIN                   |                  | 90794 |    13M|       | 15251   (3)| 00:03:04 |       |       |
    |*  5 |      TABLE ACCESS BY INDEX ROWID| SOLAR_STATION    |     1 |    78 |       |     1   (0)| 00:00:01 |       |       |
    |*  6 |       INDEX UNIQUE SCAN         | SOLAR_STATION_PK |     1 |       |       |     0   (0)| 00:00:01 |       |       |
    |   7 |      PARTITION RANGE ITERATOR   |                  |   272K|    20M|       | 15245   (3)| 00:03:03 |    10 |    11 |
    |   8 |       PARTITION HASH SINGLE     |                  |   272K|    20M|       | 15245   (3)| 00:03:03 |     1 |     1 |
    |*  9 |        TABLE ACCESS FULL        | DATA             |   272K|    20M|       | 15245   (3)| 00:03:03 |       |       |
    Predicate Information (identified by operation id):
       2 - filter("MAX_DATE_STAMP"=TO_TIMESTAMP("DATE_STAMP"))
       4 - access("A"."SOLAR_ID"="S"."SOLAR_ID")
       5 - filter("S"."CLIMATE_ID"='611KBE0')
       6 - access("S"."SOLAR_ID"='636')
       9 - filter("A"."TIME_STAMP">=TO_DATE('2004-09-08 00:00:00', 'yyyy-mm-dd hh24:mi:ss') AND "YEAR"=2004 AND
                  "A"."SOLAR_ID"='636' AND "A"."TIME_STAMP"<=TO_DATE('2004-12-20 00:00:00', 'yyyy-mm-dd hh24:mi:ss'))The result was an error:
    Error at line 0
    ORA-01843: not a valid month

  • 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

  • How would you send a date-range parameter to a SQL sproc?

    Team,
    MY ENVIRONMENT
    SQL 2005, Crystal Reports for Visual Studio 2005
    MY PROBLEM
    I am authoring both a sproc and a report, so I have full control over the design. I am a SQL expert and also a Crystal 8.5 expert.
    I have done the Sproc-Report connection dozens of times.
    Please consider along with me the sequence of creating a report based on a parameterized stored procedure.
    My sproc header is shown here:
    CREATE Procedure dbo.usp_DocumentActivityReport(
         @Department NVARCHAR(50)      
       , @DateRange  NVARCHAR(50)
    ) AS
    SELECT Col1, Col2, Col3 FROM #TEMP
    MY THOUGHT PROCESS
    @DEPARTMENT is a string. That's easy.
    @DATERANGE is a DATE RANGE and I don't know how to get Crystal Reports to prompt for a date range, so I used a String parameter knowing I can parse a specially formatted string, and knowing that I can use a formula to compute the string.
    Step 1. Create the blank report, the {?Department} parameter, the {?CreationDateRange} report parameter, and the {@DateRangeText} conversion formula that converts {?CreationDateRange} to the specially formatted string.
    Step 2. Test the stored procedure.
    Tests pass; It returns data when I run it with values, with zero-length string values, and with NULL values.
    Step 3. Tie the report to the stored procedure.
    Adding the sproc directly creates two hard-wired, undeletable parameters, and returns data columns. That's no good because the user must supply the specially formatted string for the date range. So, I try using Add Command instead, with this syntax:
    {call "EXP_TEST"."dbo"."usp_CorroDocumentActivityReport" (N'{?Department}', N'{@DateRangeText}')}
    This code is accepted, but Add Command did not create any undeletable parameters at all. I guess that's OK.
    But the worst part is that it does not show any output columns with data either! AAARGH!
    Please assist with showing me the proper order to do these steps.
    BTW, here's the VB Syntax formula for {@DateRangeText}:
    Dim min As String
    dim max as String
    if HasLowerBound ({?CreationDateRange}) then
      min = ToText(Minimum({?CreationDateRange}),"MM/dd/yyyy")
    else
      max = ""
    end if
    if HasUpperBound ({?CreationDateRange}) then
      max = ToText(Maximum({?CreationDateRange}),"MM/dd/yyyy")
    else
      max = ""
    end if
    if IncludesLowerBound ({?CreationDateRange}) then
      min = "[" & min
    else
       if HasLowerBound ({?CreationDateRange}) then min = "(" & min
    end if
    if IncludesUpperBound ({?CreationDateRange}) then
        max = max & "]"
    else
       if HasUpperBound ({?CreationDateRange}) then max = max & ")"
    end if
    'formula = min & "..." & max
    formula = "(1/1/2009...3/1/2009)"
    sorry ... cross-posted per Amit

    Ludek,
    It sounds like you and The specified item was not found. think along the same lines! I have cross-posted for both of you now!
    Please see Simple Sproc Parameters question
    ~ Shaun

  • 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
    ;

  • How to get a date range in JDBC sql

    I am using the following in my sql to get a date range... but what if the field is a timestamp will that still work or not...
    AND a.date>=? AND a.date<=?

    Suzie,
    No offence, but is there something stopping you from testing it yourself?
    Good Luck,
    Avi.

  • Compute Date Range with SQL Statement

    I'm sure there is a way to do this in SQL, but I cannot figure it out. I can write a PL/SQL script to do it, but would prefer using a SQL Statement. My database is Oracle Database 10.2.0.4.0.
    I have a table that contains information such as the employee number, department id, and the effective date of when the person started in that department. There is data in another table that I want to update their department number in based on their effective date range. If I could figure out how to select the effective date range correctly, I can do the rest.
    I have data such as:
    EMP_ID DEPT_NO EFFECTIVE
    101 1000 1/15/2001
    101 1050 5/24/2005
    101 2010 6/8/2008
    101 1000 8/2/2010
    I want to write a SELECT statement that returns something like this where the END_DATE is the day before the EFFECTIVE date and the last record does not have an END_DATE because they are still assigned to that department. Also, the first record in the column, I don't want to select a DEPT_NO because the effective date logic was added in January 2001 so if a person started back in 1985 they could have switched departments zero to many times so I'm not going to update any data for that period:
    EMP_ID DEPT_NO EFFECTIVE END_DATE
    101 1/14/2001
    101 1000 1/15/2001 5/23/2005
    101 1050 5/24/2005 6/7/2008
    101 2010 6/8/2008 8/1/2010
    101 1000 8/2/2010
    Below is a script to create the data in a temp table that can be used to write a SELECT statement on. I have added two employee records with different dates.
    create table temp_activity
    (emp_id number(12),
    dept_no number(12),
    effective date);
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (101,1000,to_date('1/15/2001','MM/DD/YYYY'))
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (101,1050,to_date('5/24/2005','MM/DD/YYYY'))
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (101,2010,to_date('6/8/2008','MM/DD/YYYY'))
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (101,1000,to_date('8/2/2010','MM/DD/YYYY'))
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (102,1040,to_date('1/15/2001','MM/DD/YYYY'))
    INSERT INTO temp_activity
    (EMP_ID,DEPT_NO,EFFECTIVE)
    VALUES
    (102,2000,to_date('6/16/2006','MM/DD/YYYY'))
    Any help is appreciated. This is probably easy, but I cannot get my brain wrapped around it.
    Thanks - mike

    select  emp_id,
            dept_no,
            effective,
            end_date
      from  (
              select  emp_id,
                      dept_no,
                      effective,
                      lead(effective) over(partition by emp_id order by effective) - 1 end_date,
                      row_number() over(partition by emp_id order by effective) rn
                from  temp_activity
             union all
              select  emp_id,
                      null dept_no,
                      null effective,
                      min(effective) - 1 end_date,
                      0 rn
                from  temp_activity
                group by emp_id
      order by emp_id,
               rn
        EMP_ID    DEPT_NO EFFECTIVE  END_DATE
           101                       01/14/2001
           101       1000 01/15/2001 05/23/2005
           101       1050 05/24/2005 06/07/2008
           101       2010 06/08/2008 08/01/2010
           101       1000 08/02/2010
           102                       01/14/2001
           102       1040 01/15/2001 06/15/2006
           102       2000 06/16/2006
    8 rows selected.
    SQL> SY.

  • How to use SQL to display Datethat falls between the date range

    Hi,
    I'm figuring out how do i use SQL to select data
    that falls between the date range stated
    (for eg. 19/02/1955 to 19/02/2003)
    I've tried :
    sql="Select * From StudentRecords WHERE DOB BETWEEN #" jTextField21.getText() "#" +" And " +"#" +jTextField22.getText;
    Using BETWEEN statment , but Between Statement isn't doing what i want..
    even those out of range are displayed... any ideas how??
    Thank yOU in advance!

    oracle:
    sql = "Select * From StudentRecords WHERE DOB between TO_DATE('07/04/2003','dd/mm/yyyy') and TO_DATE('08/04/2003','dd/mm/yyyy')";

  • Pass date range parameter  to SQL stored procedure.

    Hi,
    I'd like to pass a date range parameter from Crystal Reports to a sql stored procedure. Does anyone know if this is possible?
    I've had no problem passing standard datetime (single value) paramaters to and from but am struggling with getting a range value parameter to work.
    Environment: Crystal Reports 10/XI and SQL 2000 MSDE version or SQL 2005 Express Edition.
    Any help would be appreciated.

    C5112736 wrote:>
    > And then these 2 formulas 'Formula # 1' and 'Formula # 2' can be used to pass on to the stored procedure.
    Can someone please demonstrate exactly how to use formula results as date parameters to a SQL stored procedure?  Keep in mind, there are two parameters to the stored procedure.
    I have gleaned this much: Use Add Command and insert the procedure with
    EXEC ServerName.dbo.usp_sprocName;1 '{?StringParameter}'
    but if I try to do
    {CALL ServerName.dbo.usp_SprocName({@Formula1},{@Formula2})}
    then it gives the error "No value given for one or more required parameters". 
    Both of the parameters are VARCHAR(50).
    I have finally found this link: [http://msdn.microsoft.com/en-us/library/ms710248(VS.85).aspx|http://msdn.microsoft.com/en-us/library/ms710248(VS.85).aspx]
    This Microsoft site defines the format of the ODBC escape sequences, but I still do not know how to convince Crystal to insert it's parameter results or formula results.
    Pulling what's left of my hair out . . .
    ~ Shaun

  • SQL to select data between a date range

    Hello,
    I am a new user to HTMLDB and I have an application where I need to select the rows from a table that are between a specified date range. The table description is
    name varchar2
    class varchar2
    sal number
    hdate date
    I want to select the rows of all names between date value 1 and date value 2. The SQL query I use in SQLPLUS does not work in HTML DB. The query I used is
    select null link, name from tab_data where hdate between TO_DATE('06-JAN-04','DD-MON-YY') and TO_DATE('08-JAN-04','DD-MON-YY')
    I also have 2 date picker fields in my form and I used a similar query which did not work.
    select null link, name from tab_data where hdate between TO_DATE(:P2_DATE1,'DD-MON-YY') and TO_DATE(:P2_DATE2,'DD-MON-YY').
    Can someone help me out?
    Thanks

    To All,
    This is getting frustrating... I have tried every combination and permutation I can think of with zero success. The table column I am querying is of type date. The nls_date_format is 'DD-MON-YY' on a 10g database on Linux ES. I am using datepicker 'DD-MON-YY'. I have converted it using TO_DATE, TO_CHAR(TO_DATE(, trunc etc. Is it just my installation? I have upgraded to the latest patch, so that can't be the problem. I created various test scenarios (virgin tables, one row, etc). I've been writing PL/SQL for fourteen years and I think I'm pretty good, but I've sure run up against a stone wall here. Surely somebody has done a date compare out there...
    select to_char(to_date('06-JAN-04','DD-MON-YY'),'MM/DD/YYYY') from dual;
    06-JAN-2004
    select to_char(YOUR_DATE_COLUMN,'MM/DD/YYYY') from YOUR_TABLE_WITH_DATE_COLUMN;
    15-OCT-2004
    15-OCT-2004
    15-OCT-2004

  • SQL DISTINCT COUNT IN DATE RANGE

    Dear All
    Thanks for your attention.
    A table is storing the task summary of each order
    e.g.
    Date                            | Order Number    | Task Number
    2015-01-01 00:00:01   | ABC123456        | JOB001
    2015-01-01 00:01:02   | ABC123456        | JOB002
    2015-01-01 00:10:02   | ABC123444        | JOB001
    2015-01-01 10:12:59   | ABC123456        | JOB002   (Since the job002 is not done correctly, need to work again)
    2015-01-01 18:20:05   | ABC888888        | JOB001
    2015-01-01 20:22:42   | ABC789456        | JOB001
    2015-01-01 21:02:11   | BBB121212        | JOB002
    I would like to write a single query that get the distinct count of order number in sepcific date range
    result as expected in three columns:
    2015-01-01
    task_number            | AM | PM
    JOB001         | 2    | 2
    JOB002         | 1    | 1
    explain the figures here:
    JOB001 AM = 2 (ABC123456, ABC123444)
    JOB002 AM = 1  (two records of ABC123456 count as 1 since we would like to know the number of orders)
    JOB001 PM = 2  (ABC888888, ABC789456)
    JOB002 PM = 1  (BBB121212)
    I wrote a query get similar result but the count of order is not distinct
    SELECT task_number,
    AM=SUM(CASE WHEN date >= ('2015-01-01 00:00:00') AND date < ('2015-01-01 12:00:00') THEN 1 ELSE 0 END),
    PM=SUM(CASE WHEN date >= ('2015-01-01 12:00:00') AND date < ('2015-01-02 00:00:00') THEN 1 ELSE 0 END)
    FROM MyTable
    WHERE task_number = 'JOB001'
    Could anyone advise how to enhance this query to let the result become disintct of order number?
    Many Thanks,
    swivan

    Try
    select task_number,
    count(distinct case when datepart(hour, [date]) >=0 and datepart(hour, [date]) < 12 then [OrderNumbers] END) as AM,
    count(distinct case when datepart(hour, [date]) >=12 and datepart(hour, [date]) < 24 then [OrderNumbers] END) as PM FROM myTable
    GROUP BY Task_Number
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles
    Thank you very much,  short and good answer

  • Finding duplicates within a date range. SQL help please!!

    I have a table of records and I am trying to query the duplicate emails that appear within a given date range but cant figure it out.
    There records that it returns are not all duplicates withing the given date range.  HELP!!
    Here is my query.
    Thanks in advance.
    SELECT cybTrans.email, cybTrans.trans_id, cybTrans.product_number, cybTrans.*
    FROM cybTrans
    WHERE (((cybTrans.email) In (SELECT [email] FROM [cybTrans] As Tmp GROUP BY [email] HAVING Count(*)>1 ))
    AND ((cybTrans.product_number)='27')
    AND ((cybTrans.appsystemtime)>'03-01-2010')
    AND ((cybTrans.appsystemtime)<'03-05-2010')
    ORDER BY cybTrans.email;

    Yet another method...
    <cfset start_date = DateFormat('01/01/2007',
    'mm/dd/yyyy')>
    <cfset end_date = DateFormat('09/30/2009',
    'mm/dd/yyyy')>
    <cfset start_year = DatePart('yyyy', start_date)>
    <cfset end_year = DatePart('yyyy', end_date)>
    <cfset schoolyear_start = '09/01/'>
    <cfset schoolyear_end = '06/30/'>
    <cfset count = 0>
    <cfloop index="rec" from="#start_year#"
    to="#end_year#">
    <cfset tmp_start = DateFormat('#schoolyear_start##rec#',
    'mm/dd/yyyy')>
    <cfset tmp_end = DateFormat('#schoolyear_end##rec + 1#',
    'mm/dd/yyyy')>
    <cfif DateCompare(tmp_start,start_date) gt -1 and
    DateCompare(tmp_end, end_date) eq -1>
    <cfset count = count + 1>
    </cfif>
    </cfloop>
    <cfoutput>
    <br>There are #count# school year periods between
    #start_date# and #end_date#
    </cfoutput>

  • SQL for a Date Range

    Hi,
    I want a count of def as well as starting day of the week based on FDate week wise.
    I have build a case structure starting from beginning to end of the week. But it is not working.
    Please let me know a way where i can get a count of def for each week as well as starting day of the week.
    For the WHERE clause i have a given a date range but it should be for the last 20 weeks.
    SELECT FDate, count(def)
    from Table
    WHERE FDate > = '2008-03-17' and FDate <= '2008-08-07'
    group by FDate
    order by
    case when FDate >= '2008-03-17' and FDate <= '2008-03-23' Then '2008-03-17'
    when FDate >= '2008-03-24' and FDate <= '2008-03-30' Then '2008-03-24'
    when --------
    when --------
    end
    Please help.
    Thanks.

    Hi,
    While you could use a 20-pronged CASE statement, it's much eachier to use
    GROUP BY TRUNC (fdate, 'IW')
    TRUNC (fdate, 'IW') returns the DATE of the last Monday (12 midnight) that was on or before fdate. ("IW" stands for Iinternational Standards Organization Week.) It's an easy way to map an entire week into one value, and, unlike the 'D' format that Kevin and Guido mentioned earlier, it works the same regardless of you NLS settings.
    What if you need to combine things by week, but you want to consider Sunday the start of the week? That's 1 day earlier than the ISO Week, and instead of
    TRUNC (fdate, 'IW') you would use
    TRUNC (fdate + 1, 'IW') - 1.

Maybe you are looking for

  • Using JDBC with Oracle

    I have just completed compiling and running a simple UI through a java command line interface, however part of my program is running into a problem. I have to connect to Oracle through JDBC, but the server I am not on does not have the oracle drivers

  • Full Table Scans for small tables... in Oracle10g v.2

    Hi, The Query optimizer may select to do a full table scan instead of an index scan when the table is small (it consists of blocks the number of which is less than the the value of db_file_multiblock_read_count). So , i tried to see it using the dept

  • ICON on HR Infotypes(urgent)

    hi all, i have to provide ICON on all the HR Infotypes. so how i can do this. plz give me solution. i will award ur efforts for this thanks

  • Offline Re-organization of database

    Hi We are using SAP CRM 4.0 ( ECC 5.0) on HPUX 11.23 and Oracle 9.2.0.6 as the database. I would like to carry out an offline reorganization of the database. What are the steps involved, Do I use brtools to do this activity. Some of my tables eg BALD

  • MDM tracking READY folder

    Hi all I am looking for some solution to monitor: - exceptions and - ready folders. The idea is to have automated process to infor us about errors. We also want to monitor READY folder to check if files are staying in that folder for long and from so