Return max date records before the start date

Hello

Can anyone help please?

I have two subqueries, a tableofchildren called, the other called tableofworkers. Tableofchildren identifies the date the child started a class.

The second query, Tableofworkers, lists the workers and their history of involvement with the child. A child may have had a history with several workers. The worker has an allocatedstartdate indicating when they began to work with the child.

For my purpose, I need to return the workername and the allocatedstartdate of the worker involved with the child more recently before or at the time when the child began the course.

I have partially accomplished this with the query below. However, due to the quality of the data, the child may not always have an affected worker (allocatedstartdate) earlier or equal to the start date for the course of the child. In this case, the query fails and does not return the child record, that it excludes from the dataset.

Can anyone suggest a way to modify this query, so it acts like a left outer query and returns all the records in the child and null raising where they have no worker allocated beginning before or on the date of start of course?

Thank you! :)
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 the table tableofchildren
(ChildID varchar (6))
ChildName varchar (20),
Date of EnteredCourse,
Date of LeftCourse);

insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ("C1000", "Johnny Rotten', to_date (' 01/04/2011 ',' dd/mm/rrrr'), to_date (' 23/05/2011 ',' dd/mm/rrrr'));
insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ('C1256', 'Doris Dingle', to_date (' 12/08/2003 ',' dd/mm/rrrr'), to_date (' 16/09/2005 ',' dd/mm/rrrr'));
insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ('C3466","Bonny Boy', to_date (' 25/03/2011 ',' dd/mm/rrrr'), to_date (' 28/03/2011 ',' dd/mm/rrrr'));
insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ('C4567', 'Ghost Casper', to_date (' 21/03/2009 ',' dd/mm/rrrr'), to_date('22/04/2010','dd/mm/rrrr'));
insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ('C1245', 'Doris Dingle', to_date (' 20/11/2006 ',' dd/mm/rrrr'), to_date (' 30/12/2008 ',' dd/mm/rrrr'));


create the table tableofworkers
(WorkerID, varchar (6))
WorkerName varchar (20),
Date of AllocatedStartDate,
Date of AllocatedEndDate,
ChildID varchar (6));

insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3453', 'Ms. Whatever", to_date('12/05/2009','dd/mm/rrrr'), to_date ('2009-06-13', ' 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 (' 08/19/2010 ',' dd/mm/rrrr'), NULL,"C1000");
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3442', 'Ms. 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 (' 04/30/2009 ',' dd/mm/rrrr'), "C3466");
insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W3453', 'Ms. Whatever", to_date('01/06/2009','dd/mm/rrrr'), to_date ('2010-04-30', ' mm/dd/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', 'Ms. Jobsworth", to_date('22/11/2006','dd/mm/rrrr'), null, 'C1245');


create the table OutputWanted
(ChildID varchar (6))
ChildName varchar (20),
Date of EnteredCourseDate,
WorkerName varchar (20),
Date of AllocatedStartDate);

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'), "Ms. 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 the 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);

Published by: little Penguin November 21, 2011 07:03

What something like that?

SELECT childid
     , childname
     , enteredcourse
     , workername
     , allocatedstartdate
FROM
(
     SELECT toc.childid
          , toc.childname
          , toc.enteredcourse
          , tow.workername
          , tow.allocatedstartdate
          , ROW_NUMBER() OVER (PARTITION BY toc.childid ORDER BY tow.allocatedstartdate DESC) AS rn
     FROM   tableofchildren   toc
     LEFT JOIN tableofworkers tow ON tow.childid = toc.childid
                     AND toc.enteredcourse >= tow.allocatedstartdate
)
WHERE rn = 1

Just note that you need a different RANK and DENSE_RANK analytical ranking function if there is a chance that many workers could be attributed to the children on the same allocatedstartdate.

Tags: Database

Similar Questions

  • How to run the application startup script before the start of telnet (inetd)

    Hello

    I need to run my application startup script before the beginning of Telnet users on the server. At the present time, the script is at /etc/rc2.d/S98startup which is not useful.

    Thanks in advance...

    Published by: user4027740 on April 7, 2012 12:41

    I am inclined to ask 'why', but I refrain...

    The problem you'll have is that 'telnet' (really inetd) will be started by SMF and your app startup is a legacy script. I don't know of anyway to you allows to map addictive SMF one departure inherited. The only solution is to write a start of SMF for your application and do inetd:default require your application to be online before you start.

  • Satellite A300 will not get before the start screen

    Hi all

    had a problem with a laptop A300 about 2 to 2.5 years old. I just installed windows 7 prof and it worked fine for about 3 days and then all of a sudden it blocked start.

    He gets to the toshiba start screen and then reboots. He doesn't even try to start windows. You can go into the bios and make changes, etc., you can not press f8 to load in safe mode, only it does not even come to that.
    You can press f12 and raise the start menu and try to boot from the CD but this new fact not work and it just restarts again

    I don't know how else to troubleshoot it. I don't think it's a motherboard problem can you enter the bios.
    It could be a HARD drive problem, but then I thought it would have gave you a warning message of any (no available boot device) and you can see the HARD drive in the bios and would have thought that it would have started at least on a CD.

    The only things I can think about are drive problem HARD for the problem RAM or motherboard problem.
    I think install win 7 to 3 days there is just a huge coincidence?

    Any help would be great. Thank you

    Hi hitenkacha,

    Hmm... Which is really strange, if the laptop restarts after the Toshiba start screen but it doesn t happen if you go into the BIOS or boot menu...
    So, if you go into the BIOS and wait a few minutes, he doesn t restart?

    Yet one thing would be interesting to know: what happens if you try to boot from the recovery disk Toshiba? Generally, it should still possible to boot from this drive if it s ok.

    Check this box!

  • Preloader fills only 1/2 way before the start of the video

    I am very new to Flash CS4, but I was able to create a preloader with the help of a tutorial of Dan Carr.

    Here is my source:

    Fl.video import. *;
    Import fl.controls.ProgressBarMode;

    Set Variables
    var flvControl = display;
    var flvSource = "op.flv";

    Create the progressbar control manager event
    function progressHandler(event:VideoProgressEvent):void
    {
    var bl = Math.round(event.bytesLoaded/1000);
    var bt = Math.round(event.bytesTotal/1000);

    Update in progress...
    pb.setProgress (bl, bt);
    }

    function readyHandler(event:VideoEvent):void
    {
    Remove the progressbar when we start playing...
    removeChild (pb);
    }

    State to Set progress bar
    PB.mode = ProgressBarMode.MANUAL;
    PB. Indeterminate = false;

    Add listeners and load the video
    flvControl.addEventListener (VideoProgressEvent.PROGRESS, progressHandler);
    flvControl.addEventListener (VideoEvent.READY, readyHandler);
    flvControl.source = flvSource;

    Here is an example of the video:

    http://orthopreferred.us/test/Ortho/OP1.html

    Film load and plays but the part preloader loads only the path. How would go to have the load progress preloader completely bar and then have the start of the film?

    Thank you!

    use:

    Fl.video import. *;
    Import fl.controls.ProgressBarMode;

    Set Variables
    var flvControl = display;
    var flvSource = "op.flv";

    Create the progressbar control manager event
    function progressHandler(event:VideoProgressEvent):void
    {
    var bl = Math.round(event.bytesLoaded/1000);
    var bt = Math.round(event.bytesTotal/1000);

    Update in progress...
    pb.setProgress (bl, bt);

    {if(BL==BT)}

    flvControl.play(); removeChild(pb);
    

    }

    }

    State to Set progress bar
    PB.mode = ProgressBarMode.MANUAL;
    PB. Indeterminate = false;

    Add listeners and load the video
    flvControl.autoPlay = false;
    flvControl.addEventListener (VideoProgressEvent.PROGRESS, progressHandler);

    flvControl.source = flvSource;


    end

  • Adobe CC Plan student before the start of the course

    Hello

    I intend to have bought the plan student membership for creative cloud to adobe.

    However, I am currently intermission (which means I'm on break from my course).

    I return to my studies in 2 months.

    So my question is if I'm still able to qualify for the membership plan student while I'm warped to my class. I called my University to make sure that my name and ID were still in their system. They said, 'Yes,' I'm always classified as enrolled in the course.

    I want just a few details about my situation before you buy this plan and have questions about my situation on the track.

    Thank you.

    Request student/teacher discount

    http://www.Adobe.com/go/edu_verify_ecomm_us

    For more information about the provisions of the student/teacher, you can refer to the following information page:

    http://helpx.Adobe.com/x-productkb/policy-pricing/Education-FAQ.html#main_submit_poe

    Another good resource for information is the student and teacher edition information forum:

    http://forums.Adobe.com/community/download_install_setup/student_and_teacher_edition_infor mation_? view = discussions

    Here are some links about the Adobe student discount:

    http://www.Adobe.com/education/students.edu.html?showEduReq=Yes

    http://www.Adobe.com/education/student-eligibility-Guide.edu.html

    http://www.Adobe.com/education/students/how-to-buy-eligibility.edu.html

  • Bookmark, behavior of recording at the start of the replication Agents stopped.

    I have a few questions about two-way replication for 1 DSN on TT 7.0.5 with recording on disc.

    (1) If replication agents are stopped on the two machines, the log files will be stop being written? Or they do not accumulate?

    (2) when the agents are started, continue replication from the original bookmarks?

    I am trying to determine 2 machines become out-of-sync when agents are arrested, DSN continue to be updated, and then the agents are started.

    Thank you
    Linda

    I will answer all questions in a position if you don't mind:

    + (1) If replication agents are stopped on two machines, the log files will be stop being written? Or they do not accumulate? +

    Each stream replication (with bi-direactional there are two streams, A-> B and B-> A) has a (start, stop, failure, break) State which is independent of whether or not the replication agent is running (the replication agent is what does the actual capture, propagate, apply, recognize the steps).

    Start - journal of bookmarks are kept and if repagent reads the flow of replication occurs.

    Stop - no bookmarks are kept (the logs can be purged), no flow even if repagent is running.

    Failure - same as stop but only set automatically by the system, typically exceeding of THRESHOLD of LOG.

    Break - bookmarks keeps, no flow of replication occurs even if repagent is running

    The default state of a stream is 'start', but this can be handled through ttRepAdmin and can be set automatically if e.g. JOURNAL THRESHOLD is exceeded. So stop repagents on one or two machines does not change the State of the movement. Newspapers will be accumulated until the repagents are restarted.

    + (2) when the agents are started, they continue replication since the original favorite? +

    Yes, everything will be the original bookmarks. Note that unless you have strict support this scenario of partitioning can exacerbate problems of conflict.

    I am trying to determine 2 machines become out-of-sync when agents are arrested, DSN continue to be updated, and then the agents are started.

    As long as you have the workload of strict partitioning to ensure no conflict, then there is no problem. Without workload partitioning then the divergence is possible even in normal conditions and even if conflcit resolution is used.

    What is the best way to monitor this log space is approaching a complete state of disc?

    This really a level o/s problem. You can use a script that is executed regularly that analyzes the output of something as 'df k' or you can write an application that uses the o/s relevant calls to monitor the space in the file system. It's easier if the newspapers have a dedicated disk (which in any case, they should have for performance reasons). Side Timesten, you can use ttBookmark to see if the 'hold' LSN is starting to fall further and more behind the 'current' NSE This is an indication that the replication is not able to cope with the workload and that newspapers are piling up so.

    Chris

  • How can transfer emails to another account, but only at certain times of the day (after that reception has left and before the start of the next working day)?

    I run a private school. The receptionist left to 1800 and begins at 0900 the following day.

    How to receive email between 1800 and 0900 to my private account, but not the e-mail during business hours?

    I guess that you have a computer with Thunderbird installed.
    I imagine that you have a profile with an e-mail account that is used for the activities of the private school and the receptionist has access to this email account, if you don't want the receptionist to see your personal emails.

    I would approach this by creating "User accounts" on the computer.
    Thunderbird would work in all user accounts.
    A standard user account could be used by the recepionist which would profile with business e-mail address account.

    The main account of the "Admin" user, accessible by entering a password, have your profile and your personal email to your personal email account.
    Then you can connect to your user account, open Thunderbird and access/download your emails whenever you want. Output of Thunderbird and your user account when you are finished. The receptionist will not have access without knowing your user account password.

    Alternatively, if you use the same user account:
    If you have created another profile and added a new existing for your personal email address, then after 1800hours e-mail account, you can leave the profile used for the account of the company and open the profile with your personal e-mail account to download emails. By offering you this profile nearby and open the profile of the company before 0900hrs, then it works as expected.
    If you use the same user account, it is possible, if the receptionist knows how to open your profile and read emails. Thunderbird password manager may be used to protect access to your e-mail account password, but not stop playback of downloaded emails.
    So why it is preferable to use "User accounts" as described in the first option.

  • Key combination does not respond before the start

    Hello. I have a macbook pro 13 "2015 retina.

    The problem I have is the same as the title, but it's not regular "choose the appropriate settings startup disk' because I tried already several times.

    Mind you, none of these problems remain once Mac OS startup has finished, it is just the period prior to initialization.

    Here is the list of problems.

    1. There is a very long period of black screen (backlight on) between the startup sound and the apple logo appears on the screen.

    2. start after key combinations take a long time to register. For example, 'boot disk selection window' takes more than 2 minutes of waiting. I have to wait while pressing the option key. It also applies to enter recovery, reset pram, entering the diagnosis, enter safe mode, etc..

    3. once I finally get a function running, there is a delay of keyboard/trackpad. Interactions appear unusably slow on Boot Disk selector and Internet Recovery(wifi selection). Trackpad responds a minute after I hit, it is the keyboard.

    4. There is no wifi signal on Internet recovery for about three minutes (my hotspot is 5 cm behind my mac).

    To sum up, it feels like the processor is clocked at 5 Mhz or something.

    Here is a list of what I tried.

    1 reset the smc, pram

    2 reinstalling Mac OS

    3 internal SSD flash disk formatting and installing Mac OS

    4. remove the boot camp

    5. remove the magsafe

    6 safe mode (no matter, because I do not think it is related to Mac OS anyway)

    I have no external devices or readers, all that is present is the magsafe.

    I always have Apple Care has left, so feel free to tell me if you think it's a hardware problem. Thank you for reading, and I appreciate your help.

    Please make an appointment at the Apple Store - Genius Bar store and bring it into service. If you are in the United States or is unable to make an appointment in this way, contact your Apple store.

  • Portege M800 - SSD, lag of 30 seconds before the start after POST

    I have recently upgraded to an Intel Postville's G2 X 25 - M 80 GB SSD and experience a second rule 30 between the BIOS POST (black screen) and actual boot from the disc. Support of the Intel says that it is probably a BIOS problem and that I should install the latest firmware, which I already did (4.80).

    System: Windows 7, 127-Portege M800-127 PPM81E M800.

    Hello

    I guess that this shift will be caused due to the BIOS test. After you turn on your laptop it checks internal devices like HDD/SSD, CD/DVD disk, CPU, RAM, etc. So some of the material was originally this delay, I think.

    If the latest BIOS can't solve your problem, it would be interesting to know what is happening with a SSD of replacement. Can you check that out, please?

  • Project of breaks before the start of the animation

    Hello

    This slide worked OK until I put a few things on it. Initially, a piece of text on the slide.  Delay the first object for 4 seconds (time for the user to read the text)

    The first object seemed Ok followed by three others after their waiting period of 3 seconds.

    What is happening now is that the first object will appear after the series of 4 seconds.  Unless you click the play button in the playback control.

    I can't find a way around it and don't remember a change to get him to behave like that.

    Cap 4 btw.

    Help appreciated

    Hello

    Please post a screenshot of the slide in question so that we are able to fully display the timeline.

    Just shooting from the hip, you will probably discover an area click, button or input text area object that is originally playback on pause at an inopportune time.

    See you soon... Rick

    Useful and practical links

    Captivate wish form/Bug report form

    Certified Adobe Captivate training

    SorcerStone blog

    Captivate eBooks

  • What is the value of the start date, date in the end QueryAvailablePerfMetric method?

    The method QueryAvailablePerfMetric in the Performance Manager management entity has optional intervalId beginTime, endTime parameters.

    What is the difference in values returned by this method when the start and end dates are excluded?

    In my case, I see the same data.

    Because I do not think that same intervalId can we have different PerfMetricIds in a VMWare host, or is it not true?

    In the case of unmanaged ESX systems are provided only on statistics in real time for the current day.

    Statistics of sending hosts the vCenter Server system managing managed. The vCenter Server gathers statistics

    data performance of all systems ESX/ESXi that it manages and stores the information in its database, which constitute historical data.

    On the specification of begineTime and end in the spec would ensure only the metrics available in the specified period are gathered, if it makes a request for historical measures. These parameters will be not applicable for statistics in real time.

  • 32-Bit XP system - attempt to reinstall the start of the disc, guard blue screening.

    Hi guys, I'm sorry if it was taken up elsewhere, I took a look through other threads prior to this announcement, but were not of those who looked more closely.  Basically, I'm trying to reinstall my operating system from the top of my current installation, saving my files.  I did it before the start of the disc, but this time my XP disc does not work properly.  I tried at least 20 times, I kid you not, but if it is not a blue screen at random times all while it loads the disc components, it screens in windows ALWAYS blue step load.  I wonder, if not, how I can reinstall XP, without having to buy a new drive, is there some way I can do this?

    I posted this on other internet support forums, and it just happened to ask me HERE!
    I really hope that someone can help me, I'm trying to start the study soon and my PC is really important to me, but there is NO way I could afford a whole new operating system... so I REALLY hope that it does not come to that...

    Cheers, Jay

    Hello

    1. What is the exact error message you are getting?

    2. are you able to boot to the desktop?

    3. don't you make changes to the computer before the show?

    Please unplug all devices (except the keyboard, mouse and monitor) external connected to the computer and then try to install Windows XP.

    Provide us with the exact stop blue screen error code in order to help you better.

  • How to add a title (slide? screen?) BEFORE the video track

    Hello

    I am very new to Adobe Premiere Pro and I am trying to understand how to add a title to my project, but I don't want on the beginning of the video title in the sequence. I want to add to a black screen, perhaps with some transition effects, that will play before the video. I have to create a dark image in CS and add it as a still and just add the title to the still which I place before the start of the track audio and video has?

    I hope that there is something I can do right in the first who will give me a place to put the title before the start of my video. I don't see an option to add a blank slide or something so I can add a title to.

    Thanks for your help!

    The more I get more excited that I get, that this software is great.

    INSERT the clip of the song before your next clip.

    Checkout all the methods to make an "Insert". Its a fundamental right to assemble in an NLE

    There are several ways to create black.

    Create the color matte

    Create a black video

    An empty space in the timeline panel is black (Alpha)

  • Worker name/back and after a return both before course start date?

    Hi all

    Could someone help me with the below please?

    I have a query that back the worker assigned to a child just before where equal to the date the child begins his training course (see below). It works very well.
    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 >= tw.allocatedstartdate(+)
    )
    where rn = 1 
    However, I disocvered that not all children have a worker who they are assigned before / the day they began their courses (mainly because of the poor quality of the data, but a few good reasons why). Therefore, I need to write a report to audit history of children and worker participation including the following columns:

    The worker at a time that the child started the course (CurrDate/CurrWorker),
    The worker who began working with the child more recently to the child from any watercourse (PAWDate/PAWorker).
    The worker who began working with the child more recently after the child from any watercourse (POWDate/POWorker).
    The worker who works with the child before their course (LastDate/LastWorker)
    And how long the worker who works with the child before the end of their course was working with the child (LastWorkerLen)
    These would just return null when it is not subject to conditions.

    I'm not sure what the best approach is to do this.

    I thought I could use Min/Max, which I think should work correctly for columns to date... but it won't work for the text (workername) columns. This is because it will match the name of the worker according to the min/max value of the string, as a min/max value, will sometimes differ from the min/max value of the back and is not directly linked to the beginning dates dates/end through a relational code.

    Can anyone recommend a better/more sustainable approach to the code below?

    Thanks a lot for reading. Maketables below - output 1 is the desired result. :)
    select tc.childid, 
    tc.childname, 
    tc.enteredcourse, 
    
    min(case when tw.allocatedstartdate<=tc.enteredcourse and tw.allocatedenddate>=tc.enteredcourse then tw.allocatedstartdate end) CurrDate, 
    min(case when tw.allocatedstartdate<=tc.enteredcourse and tw.allocatedenddate>=tc.enteredcourse then tw.workername end) CurrWorker,
    max(case when tw.allocatedstartdate<=tc.enteredcourse then tw.allocatedstartdate end) PAWDate, 
    max(case when tw.allocatedstartdate<=tc.enteredcourse then tw.workername end) PAWorker,
    min(case when tw.allocatedstartdate>=tc.enteredcourse then tw.allocatedstartdate end) POWDate, 
    min(case when tw.allocatedstartdate>=tc.enteredcourse then tw.workername end) POWorker,
    max(case when tw.allocatedstartdate>=tc.enteredcourse and tw.allocatedenddate>=tc.leftcourse then tw.allocatedstartdate end) LastDate, 
    max(case when tw.allocatedstartdate>=tc.enteredcourse and tw.allocatedenddate>=tc.leftcourse then tw.workername end) LastWorker
    
    
    from tableofchildren tc, tableofworkers tw
    where tc.childid = tw.childid(+)
    group by
    tc.childid, 
    tc.childname, 
    tc.enteredcourse
    -----------------------------------------------------------

    create the table tableofchildren
    (ChildID varchar (6))
    ChildName varchar (20),
    Date of EnteredCourse,
    Date of LeftCourse);

    insert into tableofchildren (ChildName, EnteredCourse, ChildID, LeftCourse) values ('C1245', 'Doris Dingle', to_date ('2009-03-23', ' dd/mm/rrrr'), to_date (' 09/24/2010 ',' dd/mm/rrrr'));

    create the table tableofworkers
    (WorkerID, varchar (6))
    WorkerName varchar (20),
    Date of AllocatedStartDate,
    Date of AllocatedEndDate,
    ChildID varchar (6));

    insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W4587', 'Ms. Penguin', to_date('20/02/2009','dd/mm/rrrr'), to_date (' 02/28/2009 ',' dd/mm/rrrr'), 'C1245');
    insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W4587', 'Ms. Octopus', to_date('01/03/2009','dd/mm/rrrr'), to_date (' 21/03/2009 ',' dd/mm/rrrr'), 'C1245');
    insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W5982', 'Sir trout', to_date('22/03/2009','dd/mm/rrrr'), to_date (' 25/05/2009 ',' dd/mm/rrrr'), 'C1245');
    insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W4587', 'Mrs. crab', to_date('26/05/2009','dd/mm/rrrr'), to_date (' 25/09/2010 ',' dd/mm/rrrr'), 'C1245');
    insert into tableofworkers (WorkerID, WorkerName, AllocatedStartDate, AllocatedEndDate, ChildID) values ('W5982', 'Mr. Fishead", to_date('22/11/2010','dd/mm/rrrr'), null, 'C1245');



    create table Output1
    (ChildID varchar (6))
    ChildName varchar (20),
    Date of EnteredCourseDate,
    Date of CurrWorkerDate,
    CurrWorker varchar (20),
    Date of PAWDate,
    PAWorker varchar (20),
    Date of POWDate,
    POWorker varchar (20),
    LastDate date,
    LastWorker varchar (20),
    Number of LastWorkerLen);

    Connect the output 1 (ChildID ChildName, EnteredCourseDate, CurrWorkerDate, CurrWorker, PAWDate, PAWorker, POWDate, POWorker, LastDate, LastWorker, LastWorkerLen)
    values ('C1245', 'Doris Dingle' to_date('23/03/2009','dd/mm/rrrr'), to_date ('2009-03-22', ' dd/mm/rrrr'), 'Mr. trout', to_date('01/03/2009','dd/mm/rrrr'), 'Ms. Octopus', to_date('26/05/2009','dd/mm/rrrr'), 'Mrs. crab', to_date('26/05/2009','dd/mm/rrrr'), 'Mrs. crab", 15)

    Hello

    Looks like you already know how to get information about paw and pow separately.
    The curr and information on the latter is actually more simple: just look for work that has been active on the date of enteredcourse or leftcourse.
    Collect all 4 items is the trickiest part. Do an outer join of tableofchildren with each of the 4 separate result sets. Conditions corresponding to your 'rn = 1"must be part of the join condition, as information may be absent for a child.

    WITH     curr     AS
    (
         SELECT     c_curr.childid
         ,     w_curr.allocatedstartdate     AS currworkerdate
         ,     w_curr.workername          AS currworker
         FROM     tableofchildren          c_curr
         JOIN     tableofworkers          w_curr     ON   c_curr.childid          = w_curr.childid
                                  AND  c_curr.enteredcourse       BETWEEN     w_curr.allocatedstartdate
                                                           AND     w_curr.allocatedenddate
    )
    ,     paw     AS
    (
         SELECT  c_paw.childid
         ,     w_paw.allocatedstartdate                    AS pawdate
         ,     w_paw.workername                         AS pawworker
         ,     ROW_NUMBER () OVER ( PARTITION BY  c_paw.childid
                                   ORDER BY          w_paw.allocatedstartdate     DESC
                                 )                         AS paw_rn
         FROM     tableofchildren        c_paw
         JOIN     tableofworkers        w_paw     ON   c_paw.childid          = w_paw.childid
                                     AND  c_paw.enteredcourse     > w_paw.allocatedenddate
    )
    ,     pow     AS
    (
         SELECT  c_pow.childid
         ,     w_pow.allocatedstartdate                    AS powdate
         ,     w_pow.workername                         AS powworker
         ,     ROW_NUMBER () OVER ( PARTITION BY  c_pow.childid
                                   ORDER BY          w_pow.allocatedstartdate
                                 )                         AS pow_rn
         FROM     tableofchildren        c_pow
         JOIN     tableofworkers        w_pow     ON   c_pow.childid          = w_pow.childid
                                     AND  c_pow.enteredcourse     < w_pow.allocatedstartdate
    )
    ,     lst     AS
    (
         SELECT  c_lst.childid
         ,     w_lst.allocatedstartdate                    AS lastdate
         ,     w_lst.workername                         AS lastworker
         ,     FLOOR ( MONTHS_BETWEEN ( c_lst.leftcourse
                                     , w_lst.allocatedstartdate
                               )
                    )                                   AS lastworkerlen
         FROM     tableofchildren        c_lst
         JOIN     tableofworkers        w_lst     ON   c_lst.childid     = w_lst.childid
                                     AND  c_lst.leftcourse     BETWEEN w_lst.allocatedstartdate
                                                      AND     w_lst.allocatedenddate
    )
    SELECT       c.childid
    ,       c.childname
    ,       c.enteredcourse     AS enteredcoursedate
    ,       curr.currworkerdate
    ,       curr.currworker
    ,       paw.pawdate
    ,       paw.pawworker
    ,       pow.powdate
    ,       pow.powworker
    ,       lst.lastdate
    ,       lst.lastworker
    ,       lst.lastworkerlen
    FROM       tableofchildren     c
    LEFT OUTER JOIN                curr     ON   curr.childid     = c.childid
    LEFT OUTER JOIN               paw     ON   paw.childid     = c.childid
                                     AND  paw.paw_rn          = 1
    LEFT OUTER JOIN               pow     ON   pow.childid     = c.childid
                                     AND  pow.pow_rn          = 1
    LEFT OUTER JOIN               lst     ON   lst.childid     = c.childid
    ;
    
  • How to get the different records for the date max.

    Hi all

    Here is the sample sql for sample table and data.

    Create table student (dept_id number(10), first_name varchar2(10),last_name varchar2(10),join_date date,years_attended number(10));

    insert into student values (1,'Ann','Coleman',to_date('3/7/1917','MM/DD/YYYY'),4);
    insert into student values (1,'Ann','Coleman',to_date('3/7/1916','MM/DD/YYYY'),5);
    insert into student values (2,'Rock','Star',to_date('1/1/1920','MM/DD/YYYY'),5);
    insert into student values (2,'Rock','Star',to_date('1/1/1921','MM/DD/YYYY'),6);
    insert into student values (3,'Jack','Smith',to_date('7/1/1900','MM/DD/YYYY'),3);

    insert into student values (3,'Jack','Smith',to_date('7/1/1901','MM/DD/YYYY'),4);

    commit;

    I need to get maximum date records when the name and dep_id corresponds to. I wrote the query below and it becomes the expected result, but I'm not sure it's quite effective.

    SELECT s.dept_id, s.first_name,s.years_attended

    FROM (SELECT dept, MAX (join_date) join_date

    STUDENT GROUP BY dept_id) x

    Student JOIN s ON x.dept_id = s.dept_id AND x.join_date = s.join_date;

    This above query returns records like below, and this is the goal.

    DEPT_ID NAME YEARS_ATTENDED

    1                         Ann                                4

    2                         Rock                              6

    3                         Jack                              4

    Can you please let me know the query SQL I wrote is effective or not? This sample table may have less data, but I'm dealing with millions of records.

    Hello

    Thanks for posting CREATE TABLE and INSERT statement. This really helps.

    Here's a solution. I also added a name that seems logical. In which case you can delete:

    Select dept_id, first_name, last_name

    , max (years_attended) Dungeon years_attended (last dense_rank order by join_date)

    the student

    Group of dept_id, first_name, last_name;

    DEPT_ID FIRST_NAME LAST_NAME YEARS_ATTENDED

    ---------- ---------- ---------- --------------

    1 Ann Coleman 4

    Rock 2 star 6

    3 Jack Smith 4

    Kind regards.

    Alberto

Maybe you are looking for