Return max date record previous to start date

Hello,
Can anyone help please?
I have two subqueries, one called tableofchildren, the other called tableofworkers. Tableofchildren identifies the date that the child started a class.
The second query, Tableofworkers, lists workers and their involvement history with the child. A child may have had a history with multiple workers. The worker has an allocatedstartdate indicating when they first started working with the child.
For my purpose, I need to return the workername and allocatedstartdate of the worker involved with the child most recently before or at the time the child started the course.
I've partially accomplished this with the query below. However, due to data quality, the child might not always have a worker allocated (allocatedstartdate) earlier than or equal to the child's course start date. In this case, the query fails and doesn't return the child's record, excluding it from the dataset.
Can anyone suggest a way of amending this query so it acts as a left outer query and returns all the child records and null vlaues where they have no worker start date allocated before or on the course start date?
Thanks! :)
select *
from
select tc.childid,
tc.childname,
tc.enteredcourse,
tw.workername,
tw.allocatedstartdate,
row_number() over ( partition by tc.childid, tc.enteredcourse order by tw.allocatedstartdate desc) rn
from tableofchildren tc, tableofworkers tw
where tc.childid = tw.childid(+)
and tc.enteredcourse >= nvl(tw.allocatedstartdate,add_months(sysdate,-10000))
where rn = 1 desired output
CHILDID CHILDNAME            ENTEREDCOURSEDATE         WORKERNAME           ALLOCATEDSTARTDATE       
C1000   Johnny Rotten        01-APR-11                 Mrs Gerbil           19-AUG-10                
C1256   Doris Dingle         12-AUG-03                 Mrs Pepsi            12-AUG-03                
C3466   Bonny Boy            25-MAR-11                 Mrs Jones            23-FEB-11                
C4567   Casper Ghost         21-MAR-09                                                               
C1245   Doris Dingle         20-NOV-06             create table tableofchildren
(ChildID varchar(6),
ChildName varchar (20),
EnteredCourse date,
LeftCourse date);
insert into tableofchildren (ChildID, ChildName, EnteredCourse, LeftCourse) values ('C1000', 'Johnny Rotten', to_date('01/04/2011','dd/mm/rrrr'), to_date('23/05/2011','dd/mm/rrrr'));
insert into tableofchildren (ChildID, ChildName, EnteredCourse, LeftCourse) values ('C1256', 'Doris Dingle', to_date('12/08/2003','dd/mm/rrrr'), to_date('16/09/2005','dd/mm/rrrr'));
insert into tableofchildren (ChildID, ChildName, EnteredCourse, LeftCourse) values ('C3466', 'Bonny Boy', to_date('25/03/2011','dd/mm/rrrr'), to_date('28/03/2011','dd/mm/rrrr'));
insert into tableofchildren (ChildID, ChildName, EnteredCourse, LeftCourse) values ('C4567', 'Casper Ghost', to_date('21/03/2009','dd/mm/rrrr'), to_date('22/04/2010','dd/mm/rrrr'));
insert into tableofchildren (ChildID, ChildName, EnteredCourse, LeftCourse) values ('C1245', 'Doris Dingle', to_date('20/11/2006','dd/mm/rrrr'), to_date('30/12/2008','dd/mm/rrrr'));
create table tableofworkers
(WorkerID varchar(6),
WorkerName varchar (20),
AllocatedStartDate date,
AllocatedEndDate date,
ChildID varchar(6));
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3453', 'Mrs Whatever', to_date('12/05/2009','dd/mm/rrrr'), to_date('13/06/2009','dd/mm/rrrr'), 'C1000');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3442', 'Mr Toad', to_date('14/07/2010','dd/mm/rrrr'), to_date('18/08/2010','dd/mm/rrrr'), 'C1000');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W14592', 'Mrs Gerbil', to_date('19/08/2010','dd/mm/rrrr'), NULL, 'C1000');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3442', 'Mrs Pepsi', to_date('12/08/2003','dd/mm/rrrr'), to_date('22/04/2007','dd/mm/rrrr'), 'C1256');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3490', 'Mr Tomato', to_date('12/03/2008','dd/mm/rrrr'), to_date('30/04/2009','dd/mm/rrrr'), 'C3466');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3453', 'Mrs Whatever', to_date('01/06/2009','dd/mm/rrrr'), to_date('30/04/2010','dd/mm/rrrr'), 'C3466');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3457', 'Mrs Jones', to_date('23/02/2011','dd/mm/rrrr'), null, 'C3466');
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3453', 'Mrs Jobsworth', to_date('22/11/2006','dd/mm/rrrr'), null, 'C1245');
create table OutputWanted
(ChildID varchar(6),
ChildName varchar (20),
EnteredCourseDate date,
WorkerName varchar(20),
AllocatedStartDate date);
insert into OutputWanted (ChildID, ChildName, EnteredCourseDate, WorkerName, AllocatedStartDate) values ('C1000', 'Johnny Rotten', to_date('01/04/2011','dd/mm/rrrr'), 'Mrs Gerbil', to_date('19/08/2010','dd/mm/rrrr'));
insert into OutputWanted (ChildID, ChildName, EnteredCourseDate, WorkerName, AllocatedStartDate) values ('C1256', 'Doris Dingle', to_date('12/08/2003','dd/mm/rrrr'), 'Mrs Pepsi', to_date('12/08/2003','dd/mm/rrrr'));
insert into OutputWanted (ChildID, ChildName, EnteredCourseDate, WorkerName, AllocatedStartDate) values ('C3466', 'Bonny Boy', to_date('25/03/2011','dd/mm/rrrr'), 'Mrs Jones', to_date('23/02/2011','dd/mm/rrrr'));
insert into OutputWanted (ChildID, ChildName, EnteredCourseDate, WorkerName, AllocatedStartDate) values ('C4567', 'Casper Ghost', to_date('21/03/2009','dd/mm/rrrr'), null, null);
insert into OutputWanted (ChildID, ChildName, EnteredCourseDate, WorkerName, AllocatedStartDate) values ('C1245', 'Doris Dingle', to_date('20/11/2006','dd/mm/rrrr'), null, null);
Edited by: Tiny Penguin on 21-Nov-2011 07:03

Tiny Penguin wrote:
Hi Centinul.
Thanks! That looks like it's working great!
I'm confused though...aside from ANSI joins, how come this works and mine doesn't? You missed a (+) in your WHERE clause:
where tc.childid = tw.childid(+)
and tc.enteredcourse >= nvl(tw.allocatedstartdate,add_months(sysdate,-10000))In this case the second condition is applied AFTER the tables were outer joined filtering out the row from the entire resultset because the enteredcourse date was less than the allocatedstartdate
It probably should have been:
where tc.childid = tw.childid(+)
and tc.enteredcourse >= nvl(tw.allocatedstartdate(+),add_months(sysdate,-10000))In this case the second condition was applied as part of the OUTER join between the two tables, keeping the row with the child ID of 'C1245' from the tableofchildren and discarding it from the tableofworkers (due to LEFT JOIN)
ps...I hate ANSI joins! :DANSI joins rock :)
Edited by: Centinul on Nov 21, 2011 10:52 AM

Similar Messages

  • Previous month first data and previous month last date

    can any body have query to get previous month first date and previous month last date.
    Ex: First day of the previous week:
    TIMESTAMPADD(SQL_TSI_DAY,-6, (TIMESTAMPADD(SQL_TSI_DAY, DAYOFWEEK(CURRENT_DATE) *-1,CURRENT_DATE)))
    Last day of the previous week:
    TIMESTAMPADD(SQL_TSI_DAY, DAYOFWEEK(CURRENT_DATE) *-1,CURRENT_DATE)
    can anybody have it for first day of the previous month,last day of the previous month?
    Edited by: user12255470 on Apr 7, 2010 3:30 AM

    Hi,
    1st day of previous month :
    TIMESTAMPADD(SQL_TSI_DAY, ( DAYOFMONTH(TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)) * -1) + 1, TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE))
    last day of previous month :
    TIMESTAMPADD(SQL_TSI_DAY,DAYOFMONTH(TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)) * -1 , TIMESTAMPADD(SQL_TSI_MONTH, 1, TIMESTAMPADD(SQL_TSI_MONTH,-1,CURRENT_DATE)))
    Please mark Q answered and award points for correct answers !
    Thanks
    Alastair

  • Number of occurences between two dates based on a starting date + frequence

    I have a starting date in cell A1 and a frequency (in days) in cell B1. In cell C1 I have a date (begin) and in cell C4 I have a later date (end). I need to know how often the event occurs during the time between begin and end dates (inclusive).
    For instance, the starting date is january 25th, the frequency is 5. The first date is januari 25th, the second date is februari 12th. The result should be 2 (because given the starting date and frequency of the event, it will occur in februari on day 4 and 9).
    I have been looking at some of the statistical functions, but I don't think there is a function for this. Right now I have about 5 formulas to calculate intermediate results, but I'm stuck trying to combine them.
    I would be happy with just a pointer in the right direction. For instance, is there a specific name for this kind of calculation?

    michielvoo wrote:
    I have a starting date in cell A1 and a frequency (in days) in cell B1. In cell C1 I have a date (begin) and in cell C4 I have a later date (end). I need to know how often the event occurs during the time between begin and end dates (inclusive).
    For instance, the starting date is january 25th, the frequency is 5. The first date is januari 25th, the second date is februari 12th. The result should be 2 (because given the starting date and frequency of the event, it will occur in februari on day 4 and 9).
    If the event occurs every five days, the second date will be January 30, and the event will occur four times " during the time between begin and end dates (inclusive)"
    I have been looking at some of the statistical functions, but I don't think there is a function for this. Right now I have about 5 formulas to calculate intermediate results, but I'm stuck trying to combine them.
    It's not really a statistical calculation, but a simple division to find "How many whole sets of five (days) are there in the days between two dates."
    I would be happy with just a pointer in the right direction. For instance, is there a specific name for this kind of calculation?
    Two functions and one operation are needed:
    DATEDIF() to calculate the number of days between the start and end dates.
    Division to determine how many sets of five days there are in that period.
    INT() to discard the fractional part of the result.
    With the values located as described, this formula (placed in a cell on the same table) will return the number of occurrences not including the first one.
    =INT(DATEDIF(C1,C4,"D")/B1)
    To include the Start date as one of the occurrences, make this modification:
    =INT(DATEDIF(C1,C4,"D")/B1)+1
    Regards,
    Barry

  • Setting the Asset Value date as the dep start date

    Hi,
    I need to pick depreciation from the asset value date and NOT the dep start date in the asset master record. Is this possible? IF it is, then what config changes needs to be done.
    Thanks

    Hi
    You can define that in the multi level method assigned to your depreciation key.
    Assign points if the information is  useful to you
    Regards
    Sanil Bhandari

  • Variable last date of previous month/last date of current month

    Hello Experts,
    I am facing an issue while designing a query.
    Requirement is like this.
    Report will be run on monthly basis.so on execution of report, it should prompt for month/year.
    now on report there are two columns for which I have to get data on date basis(last date of previous month and Last date of current month).
    Can anyone tell me is there any standard variable for this? what is it?
    or how to achieve this?
    Regards,
    Nirav

    Hi,
    See if this post in this forum can help you.
    Re: Last date of a month
    Regards
    Shalabh Jain

  • Integration with Outlook - how to increment end date and time from start date/time

    Hi,
    I want to add a variable amount of time to an appointment start date and time in outlook, through vba in access.  Code below shows what I've done:
    ======================================
        Dim olApp As New Outlook.Application
        Dim olAppointment As AppointmentItem
        Dim myRequiredAttendee As Outlook.Recipient
        Set olAppointment = olApp.CreateItem(olAppointmentItem)    
        With olAppointment
            .Start = DateValue(strStartDate) + TimeValue(strStartTime)
            .Duration = intDuration
            .End = DateValue(strStartDate) + ????????
    =======================================
    What do I replace the ????? with so that it increments the start time by any duration I decide in minutes?  Using the duration doesn't seem to work and I also want to be able to have the appointment span a number of days, e.g. could start at 930am on
    Monday and end at 10am on Weds, but want to set the end time relative to the start time.
    Thanks,
    Chris.
    _________________________________________________________ Every day is a school day!

    I've tried that, but it throws out a datatype mismatch error :(
    It would be helpful if you posted the exact code you tried.  In my tests, setting teh .Duration property appears to work.  However, if you want to set the .End property to a specific number of minutes after the date/time of the .Start property,
    this works for me:
    With olAppointment
    .start = DateValue(strStartDate) + TimeValue(strStartTime)
    .End = .start + TimeSerial(0, intDuration, 0)
    End With
    Assuming, that is, that intDuration contains the number of minutes the appointment should last.
    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

  • Difference in Maintenance Plan date to Order basic start date

    If i creat a strategy plan and schedule, i am getting difference in PLan date in Maint plan to Basic start date. What is making this difference. How to overcome this. I need Order start date same as PLan date.
    Plz help me frnds.
    Guruprasad

    hi
    can you explain in details with your maintenance plan with the dates.Normally your call date and plan date will be different becase of call horizon ,but the order basic start date and plan date will be equal only
    kindly revert back
    regards
    thyagarajan
    your order basic date will be when you have maintenance call is generated.kindly check
    Edited by: thyagarajan krishnamurthy on Feb 25, 2009 9:46 AM

  • Basic finish date earlier than basic start date while backward scheduling

    I am encountering an issue where in when I am selecting backward scheduling for a process order and I am entering the Basic finish date, afte which system is giving me a Basic startdate which is after the basic finish date.
    For eg:- When i give the basic finish date as 08.12.2011, system is giving me basic start date as 09.12.2011
    I have checked the recipe of the material. In the recipe one major flaw that i found out was that all the activity timings were maintained as 0. But when i created a similar scenario in the testing client, i am not getting the issue.
    Please help.

    Hi,
    Check what is maintawined in number of days the start day is allowed to be in the past in scheduling parameters of the order type, in OPU3. If there is an opening float defined in schedule margin key of the order, and concerning this float backward scheduling finds a start date which falls into past, lead time scheduling will automatically switch to forward scheduling starting from today. 9.12.2011 could have been deducted this way. Also check the factory calendar if days upto 9.12.2011 are defined as working days.
    Regards.

  • Credit card start date?, Credit card start date?

    What does credit card "start date" mean?

    I was getting a strange page that looked like an old Yahoo page from the early 90's. (Links in blue underlined text, no formatting) Once I got on the live chat with Apple Support, going back to it was the familiar Change Payment screen, without the strange questions. The strange page also asked for an Issue number for the card.
    Kinda bizarre, but fixed now.

  • Data records rejected while using Data Manager Packages

    Hello all ,
    We have configured the dimensions and applications in SAP- BPC 7.5 NW. However , while loading the data into the application using a data manager package , all the records are rejected. The following is the error :
    Line 3 :Dimension: P_CC member: SALESTEAM1 is invalid or is a calculated member
    Line 3 :Dimension: PRODUCT member: PRODUCTA is invalid or is a calculated member
    However , these member are present in the dimensions and are processed as well !! Any help is appreciated .
    THanks
    Vijay

    The message seems to be saying you have a dimension forumula  defined for those two cost centers.  Please check your dimension members master data and make sure there is nothing defined in a property column called "Formula" for those two members.  If there is something populated, then delete the cell contents and save and process your dimension.  Then try your data manager load again.
    Best regards,
    [Jeffrey Holdeman|http://wiki.sdn.sap.com/wiki/display/profile/Jeffrey+Holdeman]
    SAP Labs, LLC
    BusinessObjects Division
    Americas Applications Regional Implementation Group (RIG)

  • Changing master data record while loading Transaction data

    Hello All,
    We have a requirementt to change one of the master data field(FLAG) while loading on the transaction data.
    we get the material info in the Master data. and in the sales order item data also we get the material.
    While loading the Transaction data, I have to set a FLAG field has "s" in the Master data material based on the Key selection:
    Master data -  MAterial = Tramsaction - Data Material.
    I have written the code.. and implemented.. i get the correct records but i face huge performance issue. can any one guide me please
        DATA: itab1 TYPE STANDARD TABLE OF /bi0/pmaterial,
               wa_itab1 TYPE /bi0/pmaterial,
               w_tabix TYPE sy-tabix.
         IF itab1 IS INITIAL.
           SELECT * FROM /bi0/pmaterialINTO TABLE itab1.
         ENDIF.
         LOOP AT result_package ASSIGNING <result_fields>.
           READ TABLE itab1 INTO wa_itab1 WITH KEY
                              material =  <result_fields>-material.
           IF sy-subrc = 0.
             w_tabix = sy-tabix.
             IF <result_fields>-/bic/paa1c2033 IS NOT INITIAL.
               wa_itab1-FLAG = 'S'.
               MODIFY itab1 FROM wa_itab1 INDEX w_tabix TRANSPORTING FLAG .
             ENDIF.
           ENDIF.
         ENDLOOP.
         IF itab1 IS NOT INITIAL.
           MODIFY /bi0/pmaterial FROM TABLE itab1.
         ENDIF.

    Here are some performance tips:
    Add FOR ALL ENTRIES IN result_package WHERE material = result_package-material to your select statement
    After your select statement, add IF SY-SUBRC = 0.  SORT itab1 BY material. ENDIF.
    In your read statement, add BINARY SEARCH to the end of it
    At the end of your end routine, make sure to CLEAR itab1.
    You can also increase the number of parallel processes for your DTP, and DSO activation (assuming your target is DSO).

  • Master data records for time dependant data

    Hi
    In R/3. say master data has 1500 records. In BW, while loading this, i get the same number of records in monitor.
    But when i check the maintain master data for this info object, I find each row being duplicated. The difference being the valid to and valid from date. The info object is time dependant.
    So my question is: this adjustment done...is it ok continuing forward or do we change something now so that i dont see duplicate rows?
    Thanks in advance
    AR

    hi,
    everything is ok here (I assume you have timeframes for e.g.: 01.01.1000 - 27.12.2005 and 28.12.2005 - 31.12.9999).
    If you are working on developement system now - change something time-dependent in your master data tommorow (in your source system) and extract delta. Two new periods will be created and you will have 3 records, e.g.: 01.01.1000 - 27.12.2005 , 28.12.2005 - 28.12.2005 and 29.12.2005 - 31.12.9999.
    Regards,
    Andrzej

  • How to connect start date of shape to start date from Excel column?

    I tried to create Visio report with timeline
    Created connections and add external data.
    Dragged projects to the main screen
    But, start/finish date do not connect to the project data.
    What should I check or correct?

    The shape uses a custom property for the start and end date/time (controlled by the add-in).
     Since you cannot have duplicate names for fields within the shape your spreadsheet's column name will have to be different than the solution name when it is read and linked. You might check David Parker's site for a possible solution.
    http://blog.bvisual.net/
    I remember him illustrating how to link a SharePoint list to a timeline for dynamic changes (roughly the same operation).
    al
    Al Edlund Visio MVP

  • When entering credit card details, is the date field for the start date or expiry date? [was: payment]

    I had my bank card accidently cancelled by my bank. I have entered the new card number into payment section and it is asking for a date. Is that date the time the card began or finishes - the section does not make is clear. Thanks

    I know of no banking or credit company on the planet that would ever ask or need to ask about the "beginning" date on a crdedit or debit card.
    I'd have no way of replying to such an absurd question if I were ever asked. 

  • Join two tables, return max 1 record for each left

    I want to join tables A and B, but I only want to return a maximum of one record for each record on the left.  For example
    Table A
    Bob,1
    John,2
    Jill,3
    Table B
    1,MountainTime
    1,MountainTime
    2,CentralTime
    3,PacificTime
    Result
    Bob,MountainTime
    John,CentralTime
    Jill,PacificTime

    Hi Andrew,
    Create a report by joining two tables and insert a group on code(1) and place your fields on goup footer.
    This will give only one record.
    Thanks,
    Sastry

Maybe you are looking for