How to find the difference between two dates in time except Sunday

Hi all

I have a table, as shown below.
SQL> select * from test;

TR_ID                                              CREATE_TIME                                                                       CODE
-------------------------------------------------- --------------------------------------------------------------------------- ----------
S12341                                             05-JUN-12 12.20.52.403000 AM                                                      1003
S12342                                             11-JUN-12 11.15.33.182000 AM                                                      1003
S12342                                             07-JUN-12 12.00.36.573000 PM                                                      1002
S12343                                             20-JUN-12 12.34.37.102000 AM                                                      1003
S12343                                             15-JUN-12 11.34.27.141000 PM                                                      1002
S12344                                             01-JUL-12 10.01.06.657000 PM                                                      1002
S12344                                             06-JUL-12 12.01.04.188000 AM                                                      1003
S12341                                             31-MAY-12 11.20.38.529000 PM                                                      1002
I would like to know the difference between same tr_ids create_time, which should give out in hours except Sunday.

For example:

TR_ID: S12344
1002_Create_time: July 1, 12 PM 10.01.06.657000 (i.e. Sunday)
1003_Create_time: 12.01.04.188000 AM 6 July 12

1002 create time is 22:00 Sunday.

If the query must exclude only the hours of Sunday which is 10 p.m. to Monday 00 h which is 2 Hrs.

I tried the sub query after doing a search on this forum but I am not getting the desired output.
SELECT count(*) FROM (SELECT ROWNUM RNUM,tr_id,create_time CT_1002 FROM test c WHERE c.tr_id='S12344' and 
ROWNUM <= (select (cast(a.create_time as date)-cast((select create_time from test b where a.tr_id=b.tr_id and code=1002) as date)) 
from test a where a.code=1003 and a.tr_id=c.tr_id) + 1) d 
WHERE to_char(cast((select create_time from test e where e.tr_id=d.tr_id and code=1002) as date) + RNUM - 1, 'DY') NOT IN('SUN');
Need help to get the desired o/p

Hello

If I unederstand the problem correctly, that's what you want:

WITH       got_extrema     AS
(
     SELECT       tr_id
     ,       CAST (MIN (create_time) AS DATE)     AS start_date
     ,       CAST (MAX (create_time) AS DATE)     AS end_date
     FROM       test
     GROUP BY  tr_id
)
SELECT       tr_id
,       start_date, end_date          -- If wanted
,       24 * ( ( ( TRUNC (end_date,   'IW')          -- Count -1 day for every full week
                    - TRUNC (start_date, 'IW')
             )
           / -7
              )
            + LEAST ( end_date               -- If end_date is a Sunday
                        , TRUNC (end_date, 'IW') + 6     -- consider it 00:00:00 on Sunday
                 )
            - CASE
                      WHEN  start_date >= TRUNC (start_date, 'IW') + 6     -- If start_date is a Sunday
               THEN  TRUNC (start_date, 'IW') + 6               -- consider it 00:00:00 Sunday
               ELSE  start_date
                  END
            )     AS total_hours
FROM      got_extrema
;

I guess that you don't need to worry about fractions of a second. As you did in the code you have posted, I am to convert the TIMESTAMP to date values, because of DATE arithmetic and functions are so much better than what is available for timestamps.

Basically, it's just to find the number of days between start_date and end_date and multiplying by 24, with these twists:
(a) 1 day is deducted for each week between start_date and end_date
(b) if End_date is a Sunday, none of the end_date himself hours are counted
(c) If start_date is a Sunday, then all the start_date himself hours are counted. Why these hours should be counted? Because 1 day is already being deducted for the week which includes start_date, which contains only this Sunday.

TRUNC (dt, 'IW') is the beginning of the ISO week containing dt; in other words, 00:00:00 the or before the dt last Monday. This is not the NLS parameters.

Of course, I can't test without some sample data and the exact results you want from these data. You may need a little something more If start_date and end_date are both on the same Sunday.
Whenever you have a problem, please post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) of all of the tables involved.
Also post the results you want from this data, as well as an explanation of how you get these results from these data, with specific examples.
Always tell what version of Oracle you are using.
See the FAQ forum {message identifier: = 9360002}

Tags: Database

Similar Questions

  • Find the difference between two date and time

    Hi friends,

    I wanted to find the difference between two date and time, but my qury is slightest error "invalid number."

    select sql_step_num,proc_name,run_seqno,start_date,end_date,(to_char(start_date,'HH24-MI-SS') - to_char(end_date,'HH24-MI-SS') ) as ed  
    from eval.EVAL_RUNTIME_DETAILS
    where trunc(start_date) = trunc(sysdate) 
    order by sql_step_num;

    You try to get the feel between two char strings.
    And more difference between two dates gives a NUMBER of days.
    Try this:

    select sql_step_num,proc_name,run_seqno,start_date,end_date,numtodsinterval(end_date-start_date,'DAY') as ed
    from eval.EVAL_RUNTIME_DETAILS
    where trunc(start_date) = trunc(sysdate)
    order by sql_step_num;
    
  • How to find the difference between two dates in the presentation layer

    Hi gurus,

    Hello to everyone. Today, I came with the new requirement.


    I need to know the difference between a date and the current date in the formula column application presentation layer.by.



    Thank you and best regards,
    Prates

    Hi Navin,

    TIMESTAMPDIFF function first determines the timestamp component that corresponds to the specified interval setting. For example, SQL_TSI_DAY corresponds to the day component and SQL_TSI_MONTH corresponds to the component "month".

    If you want to display the difference between two dates in days using SQL_TSI_DAY, unlike butterflies SQL_TSI_MONTH and so on...

    hope you understand...

    Award points and to close the debate, if your question is answered.

    See you soon,.
    Aravind

  • How to tell the difference between two dates

    Hello:

    I have a question on how to get the difference in quantities for two dates in the replies and dashboard.

    This is the scenario. I have two guests date and three columns. The first column must be the sum of the amounts for the first quick date. The second column should be the sum of the amounts for the second fast date. And the third column is the difference between the first two columns.

    Basically, I'm trying to do something similar to a function of sum of two lines but trying to get the difference between the two rows. Any help to solve this problem would be appreciated.

    Use the COLUMN FILTERS level...

    the first column with the first variable of date quick presentation of the filter

    Similarly, the second column in the second variable of quick overview of date filter

    Kind regards
    Rambeau

  • How to find the difference between standard edition and standard edition one

    How to find the difference between oracle database standard edition and standard edition one 64 bit

    (a) using sql
    (b) using the configuration/installation files

    How to find the difference between oracle database standard edition and standard edition one 64 bit

    (a) using sql

    Select * the option of $ v;

    (b) using the configuration/installation files

    opatch lsinventory-details

  • Find the difference between two numbers (DBL)

    Hi all

    Is there a function in labview other than the subtraction function that can find the difference between the two numbers given?

    Thank you

    Davidson


  • How to store the difference between two timestamps as a number?

    Hello
    I need to find the difference between 2 variables of timestamp and the result will be stored as a number in minutes?
    as
    declare
    timestamp (7) of the fir_timestamp: = 1 January 2012 13:30 ';
    timestamp (7) of the sec_timestamp: = 1 January 2012 14:00 ';
    c number;
    Start
    c:=((sec_timestamp-fir_timestamp)/(24*60));
    dbms_output.put_line (c);
    end;

    962813 wrote:
    declare

    -fir_timestamp timestamp (7): ='01 - jan - 2012 13:30 ';
    timestamp (7) of the sec_timestamp: = 1 January 2012 14:00 ';  Incorrect type declaration

    fir_timestamp timestamp: = 1st January 12 01.30.00.000000 PM';
    sec_timestamp timestamp: = 1st January 12 02.00.00.000000 PM';
    c number;
    Start
    c: = ABS ((extrait (HEURE de sec_timestamp) - extract (fir_timestamp TIME)) * 60) +.
    ABS ((extrait (MINUTE de sec_timestamp) - extract (fir_timestamp MINUTE)));
    dbms_output.put_line (' interval Min Total:-' | c);
    end;
    /
    declare
    *
    ERROR on line 1:
    ORA-01830: date format picture ends before converting all of the input string
    ORA-06512: at line 6

    Follow what Paul has done...

    In fact, you do not need timestamp, date data type is enough

    SQL> declare
      2     fir_timestamp date :=
      3        to_date('01-jan-2012 13:30:00','dd-mon-yyyy hh24:mi:ss');
      4     sec_timestamp date :=
      5        to_date('01-jan-2012 14:00:00','dd-mon-yyyy hh24:mi:ss');
      6     c number;
      7  begin
      8     c:= round((sec_timestamp-fir_timestamp)*24*60);
      9     dbms_output.put_line(c);
     10  end;
     11  /
    30
    
    PL/SQL procedure successfully completed.
    

    If you want to place on timestamp

    SQL> declare
      2     fir_timestamp timestamp :=
      3        to_timestamp('01-jan-2012 13:30:00','dd-mon-yyyy hh24:mi:ss');
      4     sec_timestamp timestamp :=
      5        to_timestamp('01-jan-2012 14:00:00','dd-mon-yyyy hh24:mi:ss');
      6     c number;
      7  begin
      8     c:= round((
      9     to_date(to_char(sec_timestamp,'ddmmyyyyhh24miss'),
     10             'ddmmyyyyhh24miss')-
     11          to_date(to_char(fir_timestamp,'ddmmyyyyhh24miss'),
     12             'ddmmyyyyhh24miss')
     13           )*24*60);
     14     dbms_output.put_line(c);
     15  end;
     16  /
    30
    
  • How to calculate the difference between a Date column and the Date yesterday in the analysis (in the formula in the column)

    . For example, I need to calculate the difference between a date column, 'Table_Name '. "' Column_Name ' and (Current_Date-1). I tried different ways to do this. But nothing seems to work.

    Try the below formula.

    Replace "Time". "" Date "with your column.

    TIMESTAMPDIFF (SQL_TSI_DAY, "Time". "Date", TIMESTAMPADD (SQL_TSI_DAY-1, CURRENT_DATE))

    Thank you!

  • How to calculate the difference between two times by the NUMBERS

    I'm so bothered by the fact that I can't understand that.

    Cell B2 - 08:00

    Cell C2 - 10:50

    (How can cell D2 - I get this cell to calculate the difference and say 02:50?)

    I know it's probably one of the most basic operations, but for the life of me I can't understand it. The cells B2 and C2 are formatted for a 24-hour clock. But if I tell the system to just subtract the two, I get "0,118. Everything I find on the forum search goes beyond what I need. Can someone help me?

    Thank you

    Hi sapirs,

    Departure and arrival of the cells are in Date and time with Date format: no and time: 24-hour clock.

    Formula in D2 (fill down)

    = C2−B2

    The results become a duration format, but under automatic (numbers automatically worth this format)

    If you wish, you can change the cells of lasting results.

    What Data Format have your result cells?

    Kind regards

    Ian.

  • Dynamic action - Get the difference between two dates + times

    I have problems a little dynamic to work action. I'm trying to get the time between two dates with the time difference.

    Here is what I got (this is apex 4.0):

    Two date pickers + two numbers fields (date/start/end times)

    I created a dynamic action on the page who fires on the point lose focus (above points).

    The real action for the DA is the body of the PL/SQL function:
    declare
      end_date DATE;
      start_date DATE;
    Begin
      start_date := to_char(:P1_START_DATE || ' ' || :P1_START_TIME, 'DD-MON-YYYY HH:MIAM');
      end_date := to_char(:P1_END_DATE || ' ' || :P1_END_TIME, 'DD-MON-YYYY HH:MIAM');
      :P1_HOURS := end_date-start_date;
    End;
    When I change the values on the page, I get the following error:

    AJAX call back Server error ORA-06502: PL/SQL: digital or value error: character number conversion error to set the value.

    I'm guessing that there is a problem with the date formatting, but I can't make it work. Thanks in advance!

    Hi djston,

    because you chose the dynamic action of 'Set value' with the "Body of the PL/SQL function" type you need to return the value. Try the following code

    declare
      end_date DATE;
      start_date DATE;
    Begin
      start_date := to_date(:P1_START_DATE || ' ' || :P1_START_TIME, 'DD-MM-YYYY HH:MIAM');
      end_date := to_date(:P1_END_DATE || ' ' || :P1_END_TIME, 'DD-MM-YYYY HH:MIAM');
      RETURN (end_date-start_date)*24;
    End;
    

    and P1_REQUESTED_HOURS like 'item affected. "

    Concerning
    Patrick
    -----------
    My Blog: http://www.inside-oracle-apex.com
    APEX 4.0 Plug-Ins: http://apex.oracle.com/plugins
    Twitter: http://www.twitter.com/patrickwolf

    Published by: Patrick Wolf on January 17, 2011 10:54

  • How to find the difference between the two timestamp columns

    Dear all,
    Please solve my problem,
    I have Table name of the folder that has the following columns,
    EmpID in the number column, timestamp dat
    who has the following values
    Expand | Select | Wrap | Line numbers
    EmpID dat
    ====== ====
    101 4/9/2012 09:48:54
    101 4/9/2012 09:36:28
    101 4/9/2012 18:16:28
    101 4/10 / 2012 09:33:48
    101 4/10 / 2012 12:36:28
    101 4/10 / 2012 20:36:12
    101 4/11 / 2012 09:36:28
    101 4/11 / 2012 16:36:22
    Here, I need to display the following columns

    EmpID, min (DAT) as start, max (dat) as end and difference (max (dat) - min (dat) for each day,
    for example,.
    End difference EmpID Strart
    101 4/9/2012 09:48:54 09/04/2012 18:16:28 8.28
    Like this.
    3 days different here is so it should return 3 discs with the mentioned columns above,
    Please help me find it.

    Thank you
    Kind regards
    Gurujothi

    Published by: Gurujothi on April 25, 2012 04:45

    Gurujothi wrote:
    Dear Alex,
    Thank you for your reply,
    Depending on whether you are your quesy showing it in hour and minutes format its right but you mention all rows of the query
    If the table has more than 3000 lines then how it is possible to write this much higher request,
    my table with almost 3500 lines.

    You can make a few changes in the above query I posted the last I mentioned?

    Thank you.

    Published by: Gurujothi on April 25, 2012 23:18

    Hello

    You don't need to write whole records 3000 it... alex just wrote that for example have no table as your table...
    so just use the under part of this query as in the previous post, alex:

    select empid, trunc(dat),
           min(dat) as start_dat,  to_char(min(dat), 'hh24:mi:ss') as start_dat_part,
           max(dat) as end_dat, to_char(max(dat), 'hh24:mi:ss') as end_dat_part,
           max(dat)-min(dat) diff, to_char(max(dat)-min(dat), 'hh24:mi:ss') diff_part,
           extract(day from max(dat)-min(dat)) || ' days'
           || ':' ||  extract(hour from max(dat)-min(dat)) || ' hours'
           || ':' ||  extract(minute from max(dat)-min(dat)) || ' mins'
           || ':' ||  extract(second from max(dat)-min(dat)) || ' sekas'
    from trans
    group by empid, trunc(dat)
    

    hope this fixes your need

  • How to calculate the difference between 2 dates, but with interruptions and stops between

    Hello

    How can I calculate the difference in minutes between 2 dates but taking into account the existence of a table in the Appendix, so if between start_date and end_date arguments, there is no 'work time' then this part of the time will not be included in the total difference.

    Records of the time table example:

    Time_configuration start_hour end_day end_hour
    219:00307:00
    319:00407:00

    so for example first record said that on Monday you start at 19:00 and leave the next day at 7:00 and then save the same sort of thing.

    There is an event that I want to track how many minutes lasted. for example, this event began the day 2 at 19:00 and ended the day 3 at 21:00

    Theoretically, this event really lasted: 840 minutes. This 840 minutes are within the limits of the annex.

    Thanks in advance.

    The storage of the dates not as data type DATE in most cases is bad design. In addition, how do you know what day of the date is 2 at 19:00? East - Monday 2 November 2015 or Monday, March 7, 2016? It is the same for the event. In any case, assuming that both calendar and events don't extend over several weeks:

    According to schedule)
    Select time_configuration 2, 19:00 ' start_hour, end_day 3,' 07:00 ' end_hour of all the double union
    Select 3, 19:00 ', 4,' 07:00 ' double
    ),
    event like)
    Select event_id 1, time_configuration 2, 19:00 ' start_hour, end_day 3: 21:00 ' end_hour of the double
    )
    Select e.event_id,
    Sum)
    less (e.end_day + to_date (e.end_hour, 'HH24'), s.end_day + to_date (s.end_hour, 'hh24:mi')).
    greater (e.start_day + to_date (e.start_hour, 'HH24'), s.start_day + to_date (s.start_hour,'hh24:mi'))))
    ) * 24 * 60 minutes
    Appendix s,
    e event
    where e.start_day + to_date(e.start_hour,'hh24:mi')< s.end_day="" +="">
    and e.end_day + to_date(e.end_hour,'hh24:mi') > s.start_day + to_date(s.start_hour,'hh24:mi')
    E.event_id group
    /

    EVENT_ID MINUTES
    ---------- ----------
    1 840

    SQL >

    SY.

  • How to find the difference between related areas

    Hi all
    My problem is I have a table in which each woman will be visited maximum 8 times, each woman may or may not
    given a reference in any visit which in turn women will respond to this referral in a next visit
    (not necessarily the next visit), I need to calculate the average number of visits between the visit
    in which the wife received a refferal and visit in which she responds.

    as an example

    woman_id visit_id given_referral respond_to_referral
    -------- -------- -------------- -------------------
    1 1 TRUE NULL
    1 2 TRUE TRUE
    1 3 TRUE NULL
    1 4 TRUE NULL
    1 5 NULL NULL
    1 6 TRUE NULL

    This means that visit 2 response is referral to visit 1 so the difference is 1.
    and the visit 6 response corresponds to the referral in visit 4 so the difference is 4.
    what I can't do is knowing how to know answer to visit 6 associated reference visit 4 No 1 or 2 or 3...

    and I need to find the following table of the foregoing

    woman_id difference between referral and response
    ---------          ---------------------------------------
    1                    1
    1                    2

    quick access to help please

    Published by: M.Jabr on December 14, 2009 08:05
    with t as (
               select 1 woman_id,1 visit_id,'TRUE' given_referral,NULL respond_to_referral from dual union all
               select 1,2,'TRUE','TRUE' from dual union all
               select 1,3,'TRUE',NULL from dual union all
               select 1,4,'TRUE',NULL from dual union all
               select 1,5,NULL,NULL from dual union all
               select 1,6,NULL,'TRUE' from dual
              )
    select  woman_id,
            diff
      from  (
             select  woman_id,
                     visit_id - last_value(case
                                             when given_referral is not null
                                               then visit_id
                                           end
                                           ignore nulls
                                          )
                                over(
                                     partition by woman_id
                                     order by visit_id
                                     rows between unbounded preceding and 1 preceding
                                    ) diff,
                     respond_to_referral
               from  t
            )
      where respond_to_referral = 'TRUE'
    /
    
      WOMAN_ID       DIFF
    ---------- ----------
             1          1
             1          2
    
    SQL> 
    

    SY.

  • How to get the difference of two dates in months

    Dear friends,

    I have 4 items on my page.

    2 entered message text (value of loan, monthly deduction)

    2 are message style fields (start date, end date)

    I need to get the difference from above 2 dates in no.. of months. (for example say N)

    So with N, loanvalue should be divided and populated as monthly deduction.

    I tried this way, but not able to get the difference of dates

    {if ("populateMonthlyDeduction". Equals (PageContext.GetParameter (EVENT_PARAM)))}

    System.out.println ("enter populateMonthlyDeduction loop1");

    String xxDeductionStartDate = vo.getCurrentRow ().getAttribute("DeducStartDt").toString ();

    System.out.println ("xxDeductionStartDate is:" + xxDeductionStartDate);

    TXN OADBTransaction = am.getOADBTransaction ();

    java.sql.Date DeductionSDate = null;

    java.sql.Date DeductionEDate = null;

    if(xxDeductionStartDate!=null)

    {

    java.sql.Date startDate = txn.getOANLSServices () .stringToDate (xxDeductionStartDate);

    DeductionSDate = startDate;

    System.out.println ("DeductionSDate is:" + DeductionSDate);

    }

    String xxDeductionEndDate = vo.getCurrentRow ().getAttribute("DedEndDt").toString ();

    if(xxDeductionEndDate!=null)

    {

    java.sql.Date endDate = txn.getOANLSServices () .stringToDate (xxDeductionEndDate);

    DeductionEDate = endDate;

    System.out.println ("DeductionEDate is:" + DeductionEDate);

    }

    int difInDays = xxDeductionEndDate-xxDeductionStartDate; -Please correct me

    How reach it .plz help.

    Thank you

    Aravinda

    I used a custom like this method and calls this method daysBetween PFR.

    I got it. Thanks to you all.

    public int daysBetween(As Date, Date etDate)

    {

    return (int) ((etDate.getTime () - stDate.getTime (()) / (1000 * 60 * 60 * 24));

    }

    If ("populateMonthlyDeduction". Equals (PageContext.GetParameter (EVENT_PARAM)))

    {

    System.out.println ("enter populateMonthlyDeduction loop1");

    String dedStDt = vo.getCurrentRow ().getAttribute("DeducStartDt").toString ();

    String dedEndDt = vo.getCurrentRow ().getAttribute("DedEndDt").toString ();

    If (! dedStDt.Equals (null) &! dedEndDt.equals (null))

    {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    Date sdate = new Date();

    Date edate = new Date();

    String sdate1 = null;

    String edate1 = null;

    try {}

    sdate = dateFormat.parse (dedStDt);

    EDATE = dateFormat.parse (dedEndDt);

    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd-MMM-yyyy");

    sdate1 = dateFormat1.format (sdate);

    edate1 = dateFormat1.format (edate);

    int days = daysBetween(sdate, edate);

    int diffInMonths = days/30;

    System.out.println ("days is:" + days);

    System.out.println ("diffInMonths is:" + diffInMonths);

    String sTotValueTuitionFees = vom.getCurrentRow ().getAttribute("TotValueTuitionFees").toString ();//pageContext.getParameter("LoanValue").toString();

    int iTotValueTuitionFees = Integer.parseInt (sTotValueTuitionFees);

    int iMonthlyDeduction = iTotValueTuitionFees/diffInMonths;

    String sMonthlyDeduction = String.valueOf (iMonthlyDeduction);

    System.out.println ("iMonthlyDeduction is:" + sMonthlyDeduction);

    OAMessageStyledTextBean bMonthlyDeduction = (OAMessageStyledTextBean) webBean.findChildRecursive ("MonthlyDeduction");

    bMonthlyDeduction.setValue (pageContext, sMonthlyDeduction);

    }

    catch (ParseException exception) e

    {

    }

    }

    }

  • How to calculate the hours between two dates by the numbers

    If I update 09:00 start time 17:00 end time of shift in C3 and B3, how to use a D3 formula to calculate the number of hours between the two?  Then I can just copy down the lines for nth years...

    It is a spreadsheet of the part-time staff payroll.

    I'm sure that a lot of people out there have done that.

    Help, please.

    Thank you.

    Eddie

    What program of worksheet that you are using? Since you have a newer iMac running El Capitan, I can safely assume that you use NOT AppleWorks, which is a Power PC application that can run on any OS newer than the snow leopard, OS X 10.6.8.

    If you use numbers, try to repost your question in numbers for Mac forum. If you use Microsoft Excel, try posting in the Microsoft forums. LibreOffice also has community support.

Maybe you are looking for

  • Airport devices not found

    Hello! I have two devices from the airport: on the one hand at home and a time in my lab Capsule. I was away for 20 days and yesterday, when I came back, there was a problem with the two: my Mac cannot access these devices, they can connect to wifi n

  • iDVD and airplay

    My USB drive super will not a dvd using the Air game.  The video is shown as a gray screen and the audio is read the dvd will play correctly and can be seen on my iMac.  Airtime will be sent to all other types of videos and music to my tv.    My appl

  • Need drivers for Compaq Presario sg3350IL for winxp

    Hello world Need drivers for Compaq Presario KN220AA - ACJ SG3350IL for winxp. Help, please.

  • as the sucede a mi facebook

    No I can access a mi cuenta facebook

  • Low disk problem

    I have a low disk problem that I am having 40 GB hard disk and using Vista Ultimate as the operating system. How can I remove the space and which are the files may be deleted. Currently, I have removed most of the software.