How would you write this query efficiently?

I am having a problem doing a particular join in the most optimal fashion, and this kind of join I do often, so I'd like to learn the best way to do it so I can re-use the same logic every time and be comfortable that it is the most efficient means.
I am using Oracle 11g, and the situation goes like this -- well actually there is a variation of this particular situation, I'll explain the easier one first):
Table PARENT (
PARENT_ID NUMBER [PK],
(OTHER IRRELEVANT DATA COLUMNS)
Table CHILD (
CHILD_ID NUMBER [PK],
PARENT_ID NUMBER,
CHILD_VALUE VARCHAR2(50),
START_DATE DATE NULL(NO),
END_DATE DATE NULL(YES)
I want to query from PARENT, joining to CHILD when possible (e.g. an outer join) but I only want the MOST RECENT record. MOST RECENT means that it is the record with the latest START_DATE, which is a column that cannot be NULL.
I usually try a query where I make a inner SELECT in the FROM clauses, then do an outer join against it. But this seems ot be a terrible practice that slows the query down drastically, because looks like the DB analyzes that sub query for the entire DB before joining on my particular result set. Like the main query might filter it down very quickly to a small set of records, but that sub query still analyzes the entire table then joins to my subset. So something like this:
SELECT
p.(WHATEVER COLUMNS FROM PARENT),
x.CHILD_VALUE,
x.START_DATE,
x.END_DATE
FROM PARENT p,
(SELECT c1.PARENT_ID, c1.CHILD_VALUE, c1.START_DATE, c1.END_DATE
FROM CHILD c1
WHERE c1.START_DATE = (SELECT MAX(START_DATE) FROM CHILD)
) x
WHERE
p.(FILTERING ON PARENT)
AND x.PARENT_ID(+) = p.PARENT_ID
Then a variation of this is that the CHILD table has one other column:
CHILD_TYPE (NUMBER)
And I need to join on the CHILD getting the MOST RECENT record for each CHILD_TYPE... for this I do two inner queries usually, and again I know its not the right way to do it.

with most_recent_child as (
                           select  *
                             from  (
                                    select  c.*,
                                            row_number() over(partition by parent_id order by start_date desc) rn
                                            from  child c
                             where rn = 1
select  *
  from      parent p
        left join
            most_recent_child c
          on p.parent_id = c.parent_id
/SY.

Similar Messages

  • How would I write this query

    [USERNAME]
    [GROUP]
    User1
    New Member
    User2
    New Member
    User1
    All Members
    User1
    Gold Member
    How would I write a query so that I could select * from the above table where a user has more than 1 group (user1) and if one of the groups = 'All members' then ignore that row and just return the all the other rows for the user that has > 1 group. 
    Thanks in advance.  I can write the query for counting if a user has more than 1 group, but I stuck on the rest.
    Thanks again

    Try this
    declare @tab table(USERNAME varchar(10), Usergroup varchar(15));
    insert into @tab values
    ('User1','New Member'),
    ('User2','New Member'),
    ('User1','All Members'),
    ('User1','Gold Member');
    select * from
    (Select *,ROW_NUMBER() OVer(partition by username Order by case when Usergroup ='All members' then 0 else 1 end desc) RN From @tab ) t
    where t.usergroup= case when t.rn >1 and t.Usergroup='All members' then 'Do not return' else t.Usergroup end
    Satheesh
    My Blog |
    How to ask questions in technical forum

  • I need to change my apple id in my ipod (it was an old email address).  How would you do this?

    I need to change my apple ID in my ipod touch (it was an old email address).  I have changed to setting in itunes.  How would you do this? - not sure what my OS is.

    Go to Settings>Store (or Settings>iTunes and App Stores for iOS 6) and sign out and sign in with the other/updated account.

  • Advice - how would you do this?

    I have a compound path (an inner rectangle and an outer one) in an opacity mask. I have to apply an b/w gradient from the outer to the inner ractangle.
    I can only find a feature to add circular an linear gradients!
    How would you do this?

    haemse,
    Transitions like this are made with Blends; Object>Blend>Options to ensure the options you want, then Object>Blend>Make.
    In this case you may:
    1) Object>Compound Path>Release;
    2) For each rectangle, set Stroke to the Fill Color and set Fill to None;
    3) Select both and Object>Blend>Make (keep it Smooth).
    In other words replace the Compound Path with a Blend.

  • How would you do this? - Using a laptop as a capture device?

    I have noticed that most camcorders can only record 2 independent audio tracks. I have a situation where I need to recored 4 separate audio tracks. I have noticed in the Log an Capture window that it is possible to record more than 2 tracks at once... How do you route this (What interface works best?)
    My second question is I have seen there is a huge move to go tapeless (Which I would love to do)... I have played around with hooking up my MacBook Pro, External Hard Drive, and my camera... and then launching FCP and capturing ... (The quality is outstanding) and it really saves time because you don't have to import from a tape.... So here is my question... How could I route 4 independent mics, AND would this work if I recorded for over an hour? (I often record musicals that run at least an hour)...
    Thanks to anyone that can help!!!
    Gary

    First, I believe there is a 4 hour limit on LIVE captures. We've done up to 2.5 hours, in the past. I don't know how a long live capture with 4 channels of audio might affect this.
    RE: "Live capture quality is outstanding"...I'd advise that you roll tape as a backup. Should 'ANYTHING' happen to the live capture, you'll be hosed...(Mr. Murphy guarantees it)
    I've not captured 4 channels, but Andy Mees posted this bit of advice awhile back...
    "use a DV deck like the DSR-1500 together with a capture card, like the Decklink or Kona or Pipe cards. then using the SDI output from the deck you can happily capture 4 channels. likewise for your live input."
    ...from this thread:
    http://discussions.apple.com/thread.jspa?messageID=2953885&#2953885
    Straight FW capture is limited to 2 channels of audio. Most often people simply capture in two passes (as discussed in aforementioned thread).
    There are probably other solutions...I just wanted to ask if Duran's Pharmacy is still serving awesome New Mexican cuisine?
    K

  • How Would You Do This Effect in Logic?

    I'm trying to figure out how I would best achieve the vocal effect in Kesha's song "BLOW."
    http://www.youtube.com/watch?v=_USZ2D0GTxo
    In the chorus, there is the catchy "blow....oh...oh..oh..oh..oh..oh" section. Someone suggested she sings the entire line, which gets interrupted by a gate, which could be triggered by a keyboard, so everytime you hit a note, it stops the steady note she's singing. If you guys think that's what they are doing, how would I set this up? This kind of thing goes on in modern pop all the time and I have to find a way to do this effect before it drives me crazy;)
    I get hired to do karaoke tracks all the time and whenever there is one these to day it is always a pain due to my being more a traditional guitar, keyboard "organic" producer than synth/FX guy.
    Thanks for any help.
    Tom

    Thanks David.
    The plug ins you mention don't really help though, because they can only be set to preset patterns. This is a specific pattern of course. I know The Bee Gees did this in Robin Gibb song from the 80s called "Boys Do Fall In Love" ....there was a section that went "B......B...B...Boys fall in love." They did it by sampling the phrase into the Emulator back then and playing the phrase. I guess I could do that with EXS.
    The best solution would be if there was a way to make a gate respond to a midi track, so I could play the rhythm on the midi track, quantize it, then use that as a trigger to the gate...gonna try that...Guess I could also record the midi track as a sidestick or something and use that audio track to trigger the gate....hmmmm.
    Tom

  • How would you write a "wildcard" in a filefilter?

    How would you go about to have a wildcard instead of the "*" in the following filefilter;
              File[] files = new File("./resultat/resultat_" + "*" + "_" + index[0]).listFiles (new FileFilter () {
                    public boolean accept (File file) {
                        return ! file.isDirectory ();
              });All help appriciated
    - Karl XII

    Shouldn't "a*" accept all files that begins with "a" and ends with whatever?No. "*" in regexp is a not a wildcard match. Instead it matches one or more instances of the preceeding
    value.
    Therefore "a*" will match "a", "aa", "aaa", "aaaa" etc but will not match anything which does not end in
    an "a".
    The following might help you out. (not the most elegent expression but it will do
    import java.util.regex.*;
    public class RegExp{
      public static void main(String[] args) {
      Pattern p = Pattern.compile("a*b");     
      Matcher m = p.matcher("aaaab");     
      System.out.println(m.matches());                    
      // interesting bit here
      // match one or more occurances of any characters in the ASCII charset  (the \\p{ASCII}* bit   
      p = Pattern.compile("hello_\\p{ASCII}*_b");     
      m = p.matcher("hello_wibble_b");     
      System.out.println(m.matches());
    }

  • Dates : How would you do this.

    mx:DateChooser has a selectableRange property where you can set a rangeStart and a rangeEnd...
    Is it possible, or how would you go about doing it so it's a nonSelectable range.
    a user clicks on 3 days, so the calendar marks that off, so another user won't be able to select those same 3 days type of thing...

    d'oh
    .disabledRanges
    *SIGH*

  • How would you write a code to automate this??

    Hi team,
    Still trying to improve my coding..
    So I have got all of these buttons... how would I go about coding so I dont have this function repeated 100 times??
    Cheers,
    Sub
    e.g.
    GSmain.gsshape.gss1.gssr.gssr1.addEventListener(MouseEvent.CLICK, page2go)
    function page2go(e:MouseEvent){
              gotoAndStop(2);
    GSmain.gsshape.gss1.gssr.gssr2.addEventListener(MouseEvent.CLICK, page3go)
    function page3go(e:MouseEvent){
              gotoAndStop(3);
    GSmain.gsshape.gss1.gssr.gssr3.addEventListener(MouseEvent.CLICK, page3go)
    function page3go(e:MouseEvent){
              gotoAndStop(4);
    etc etc

    // loop from 1 to 100
    for(var i:int=1;i<=100;i++){
    // use array notation to coerce flash to convert strings to objects
    GSmain.gsshape.gss1.gssr["gssr"+i].addEventListener(MouseEvent.CLICK, pagego)
    function pagego(e:MouseEvent){
    // gssr1,gssr2,etc are all currentTarget event dispatchers. one of them called this function.  to find which, use the flash string methods.
    // e.currentTarget.name is a string like "gssr1","gssr2",...,"gssr100"
    // the String.substring(n) method returns a substring of String starting at index n.
    // so e.currentTarget.name.substring(4) is "1","2",...,"100" depending on which object was clicked
    // int("n"), converts a string to an int for use in the gotoAndStop() method:
              gotoAndStop(int(e.currentTarget.name.substring(4)));

  • Had you been the customer support,how would you resolve this?

    Hi community,
    i would like to have your opinion on this matter
    i purchased a macbook pro 45 days ago
    and i noticed recently that the lid does not close flush with the bottom part of the unit.
    so i broght it to the apple store to have a look at it
    they asked me what happened, i answered exactly like this:
    -i think i have never noticed because it is not 100% apparent to the eye but i never dropped my laptop and as you can see there is absolutly no DENT at all
    the co worker named yoan did not believe one word from what i said and told me:
    -i will exceptionnally replace the screen for you
    i was like what?
    -i only had it for 45 days, are you going to make my laptop 1/2 original half rebuilt?
    i said no way that i spent $1500 to have my laptop rebuilt after only 45 days, so i asked for an exchange given that my macbook has NO SCRATCH whatsoever.
    from then on,they have never looked back to my suggestion of exchanging my laptop and they kept telling me,all i can do is put a new screen to it (VERY FLEXIBLE!!)
    SO ALL I WANT IS YOUR OPINION POPULATION!!
    i escalated this to 4 managers that kept saying the ONLY 1 SOLUTION that is written on my case
    i am willing to attach pictures to show how unfair the apple co workers were to me.
    i had not a single scratch on my laptop and i think that MY ONLY MISTAKE was that i did not realize this in my 14 days of purchase (apple refund policy)
    this is my case# 248432100.
    i attached pictures to this message, if you need more please let me know.
    please feel free to send me your opinion by email or ask for pictures as i will send them HD to prove that i was duped by apple
    this was my 5th apple product and if i can have YOUR OPINION on this, i want to know if i am willing to do business with this company in the future or im i the only one that is missing something here.
    my justification as to why i did not want to change the screen lid is the following:
              -i like to preserve originality of my items (especially if i paid $1500)
              - i have experience in the past where i had an iphone 4, and when they changed the back glass they had blocked the flash from working properly
    Please take sometime to give me your opinion on this community
    MY EMAIL IS : [email protected]
    Thank you   

    You had 14 days from the date of your purchase to inspect your MBP and exchange it. After that time expired, the window of opportunity for an exchange closed. You are now a candidate for a warranty repair, which has already been offered to you. All of the foregoing is standard Apple policy and practice, applicable to you and to everyone else. But you don't trust Apple to repair your new machine. Where would you be if it actually had a serious problem?
    Do you object to having your car repaired, too?

  • How would you do this style of scrawling if thats what its even called ?

    just how the words are so animated and they move and explode into different things
    http://youtu.be/KnnYiW5dnhQ

    ok so what your saying is once i am familiar with the basics, how to do something as complex as this would be just a matter of putting together a couple different steps i learned along the way that would lead to this i.e. tracking text to shape and etc .. i can definitely understand that because thats pretty much how i learned to edit video based off of those principals, I'm just trying to give myself something to come back and look at it when its time to move up because honestly im trying to have something like this usable by september for a project that will huge... as an amateur/pro cinematographer i have garnered millions of youtube hits in the music field, and now I'm trying to build some more unique skills that would rival some of the best.
    ps im a  fast learner so don't hesitate to drop anything on me i might not be ready for because even if... i will take a step like you suggest and come back with a better mind set to comprehend the information

  • How would you create this effect?

    I am curious if there is a fairly straight-foward away of creating the effect seen in this image. I am talking about the pixelated effect made up of many little red boxes of various hues at the top part of the image.
    I was thinking of zooming in real close to an image in photoshop and doing a screen capture, but I'd rather have a vector image that can be easily scaled in size and easy to change the hue to different colors.
    Something like this able to be done in illustrator without building it a box at a time?
    Regards,

    Well I'd say that PDF is a vector.
    The PDF contains nothing other than a raster image. It contains no vector paths.
    (By the way: "A vector" is a single expression of a direction. Calling a vector-based illustration "a vector" is like calling a raster-based image "a pixel.")
    I zoomed in as close as I could and didn't see any pixels.
    All you could see is pixels. That's all that's there.
    If it's raster I'd be interested in knowing what resolution...
    Its resolution is 1. It's a single-pixel raster image (as given away in its title).
    I've never experienced a raster image that didn't get more pixelated the larger you scaled it up.
    Yes, you have. That's exactly what I demonstrated in post 5 and in the PDF.
    The operative word in your comment is more pixelated. That misconception is the point of the demonstration. Your image is already pixelated, and that's exactly what you want. It won't be "more" pixelated whatsoever, no matter how large you scale it.
    At the heart of the [quite common] misconception is this: What you are calling "resolution" is not. True resolution is the measure of the amount of information contained. A raster image contains only a fixed amount of information. PPI is merely a scale factor. It's merely an expression of information density, not quantity. As you can see, that PDF is every bit as "resolution independent" (i.e.; scaleable) as a vector square.
    The same priciple applies to your raster image. Your whole intent in your posted example is to display pixelation. So if the very thing you're trying to depict is the pixelation of, say, a 10 pixel x 20 pixel raster image, then all you need in order to depict that at any scale is a 10 pixel by 20 pixel raster image. At a scale of 10 PPI, you've got a perfect depiction of 10 square Pixels Per Inch. At a scale of 200%, you've got a perfect depiction of 5 square Pixels Per Inch (i.e.; 10 Pixels Per 2 Inches). You can scale it to the size of the moon and you'll have a perfect depiction of 10 Pixels Per Moon. It's just as scaleable as a 10 x 20 array of vector squares.
    In other words: All the actual resolution of your raster image (all its information—all its pixels, in all their squareness) is already visible. Reducing its information density (by scaling it larger) will not reveal more of its actual information (the square shape of its pixels—the information that one usually wants to conceal or disguize about raster images, but not in this case).
    The whole purpose of making sure your raster images have "sufficient resolution" in desktop publishing is to disguise the squareness of their pixels (what is commonly called "pixelation"). But that is exactly what you are intending to depict in this case. And you want to be able to depict that with equal clarity at any scale. There's no need to re-draw it as vector paths in order to do that. In this situation, you are not trying to avoid "pixelation," you are trying to show it, which is exactly what a raster image does by its nature.
    Think of it this way: If all you are trying to draw is 200 squares, it can easily be argued that a raster image is more "data efficient" than a file containing 200 square vector paths. For each vector path, you have to include four coordinate pairs (800 anchor points). For a raster image, all you need is 200 color values.
    This is not just a symantic or academic or pompous know-it-all point of argument. It's a point widely applicable to many common situations, and something every graphics professional should understand. For example, consider the software instructions author who pointlessly frets over the misunderstood "requirement" for pixel density when his illustrations necessarily consist of screenshots that are, after all, supposed to accurately and clearly depict what the user sees on his screen. Or the fact that you see single-pixel raster images scaled to the full width of the page, or dimensions of a table cell or large section of a whole background on web pages everyday. Or the widespread misconception that intentionally fuzzy raster effects like soft drop shapows "require" 300 PPI.
    JET

  • Secure redundant network, how would you do this?

    I'm just kind of curious what people think of this. I interned at the local county about a year ago. I noticed something that kind of bugged me. They have all their 911 dispatch stuff done on computers. They have this setup called computer aided dispatch I think it has a lot to do with like records of individuals, etc. Which all seemed quite critical.
    I didn't like the setup much though because they had 3 systems I'm pretty sure all went to the same switch and there was only a single server for this software, it used tape backups which if they had to use offsite one would then be 2 days old. (I guess the software vendor set all this up. besides a fiber which would have split off for other county offices.)
    For me I saw so many possible issues with that I think may be why they are changing vendors now.
    It would cost $$ but this would be my...

    Hi everyone,I have a user connecting to a Server 2008 R2 RDP server. He can connect no problem, but there is quite a bit of latency which I do not understand. He pings to the server at around ~60ms. I have another server on the same site (Server 2012 R2) and he does not experience the same latency. I've connected another Windows 8.1 computer to the Server 2008 R2 box and CANNOT replicate the issue.He appears to be the only one.I've temporarily disabled his AV, windows firewall, disabled local visualization settings (and on the server). I've configured RDP to 56k settings in the Experience tab which changed absolutely nothing.I've also run the netsh commands everyone seems to suggest with this issue.Any recommendations or things to try?EDIT: I've also updated his wireless drivers. I don't have the laptop in hand to try the local...

  • How would you model this? Kind of different...

    Bit of a long-winded background to what we have here. Sorry... We are building a new warehouse. Data comes from shops around the world - machines that use Cad to cut material. Two main metrics - the job_run and each of those can have many cuts. In the warehouse I had planned on building out on a time dimension of day, and the our location (down to machine), material, and some other dimensions. The fact table kept the total length of cuts, number of cuts, total length of job, number of jobs, - all per day etc. Seemed pretty straight forward.
    Then, we got some requirements on some of the questions they want answered. For example, how many cuts took longer than 30 seconds in a given day? Well, I had thought maybe I create another column in the fact table that just stored this metric and calculated it when we did the nightly load. But... we were told there could be many more of these types of ad-hoc queries - and I don't want to keep recoding the load.
    So, we realized we need to store each cut and job and their length and other attributes in the fact table - no roll up. What I'm wondering is... with this level of detail, the current dimension keys won't make each row unique. I basically need each cut ID, but is that a dimension? Is it normal to just store an ID with no dimension as part of the composite key? I thought of adding that to a dimension with job... but that seems odd. For example, some jobs have no cuts (they fail) and they want to know how many. Kind of hard when you don't have any rows in the fact table for that. Almost thought of another fact table for job... Anyway, this threw me for a loop.
    Thoughts on how others would do this?

    Thanks - yes, I've started looking at this stuff. I think I was preoccupied with using the dimension PKs to make the composite primary key for the fact table. I think it's best just to use the cut ID. The other issue was the "what doesn't happen" events. It's like having an order with no line items. If I've got no cut for a job, there's no point in creating one (like an outer join) since there's a lot of these. (User error, bit breaks, etc.) I think the idea of having a separate table for these I can get the failed jobs only...
    Thanks guys.

  • Is it possible to add a stroke to a placeholder? OR how would you do this?

    Hi there
    Basically here is a screenshot of a show im doing at the moment
    http://www.firstimage.co.uk/temporary/printingshow.jpg
    I was just wondering what people think could be done a master slide with this show? at the moment ive basically just got the text and the swirly lines in the master. the image im importing every time, rotating, resizing, and then adding a stroke. and im just copying and pasting the logo over, because it animates on in the first slide, but not the rest. basically is there any easier way of doing this with a master slide? when i tried defining the image with the stroke for the slide, it makes all other images on the slide stroked as well which is a real shame...
    any tips would be much appreciated!
    thanks
    dan

    hey tulse, thanks alot for your help, much appreciated.
    I just wanted to ask you one other thing, completely unrelated. I see that you are based in Toronto. Basically I am based in London UK but have been thinking for a while about trying to move to Canada for a while to work...I was thinking ideally Vancouver cause i heard thats really nice, but also heard good things about Toronto. Either would be awesome really. I was just wondering if there is much work in Keynote/After Effects, as that is the kind of thing I've got experience with, and how hard it would be to get work as someone from the UK. If you know any places worth checking out that'd be awesome too.
    I realise its pretty unrelated but thought it can't hurt to ask!
    Thanks
    Dan

Maybe you are looking for

  • .PDF files in DVD ROM content

    I am using a Mac and Encore CS4. I am trying to include a .pdf file as DVD ROM content. Whenever I try this, all .pdf files are "grayed out" and I can't use them. Adobe Acrobat Reader 9 and Adobe Acrobat Pro are both installed on the computer. I can

  • Combining files that are opposite pages

    using a Lexmark X854e, it will scan both sides of a 2 sided document but the process seems to take longer than if I were to scan it twice as a one-sided document.  The problem is then having 2 files.  How can I combine the files and tell it to sort t

  • Key Command for Closing Plug Windows Gone 4-Ever?

    I know there's a command for hiding plugin windows, but that's not quite the same thing... I'm sorely lamenting the (apparent) loss of the L7 key command for closing plugin float windows. Seems like it's a mouse-only operation now. Or is it? Please l

  • Is it possible to have two at selection-screen events in a program

    Hi all,      I have a selection screen wherein i am using i have 5 radiobuttons and 3 select-options and a parameter. I am trying to use two at selection-screen events 1) at selection-screen on radiobutton group rad1. 2) AT SELECTION-SCREEN ON VALUE-

  • Why does the Smart Object state affect the Detail settings in Raw?

    I've noticed that when I return from PSD to RAW in the Smart Obeject mode, the settings I had set in the Deatail panel have changed. Specifically, the Amount slider is always returned to its default position. Is this normal? Has my sharpening been al