Best way to select match on collection of values

Suppose two tables that are related by a third:
TABLE_ONE
     one_id NUMBER
TABLE_TWO
     two_id NUMBER
TABLE_THREE
     one_id
     two_id
one_id and two_id are primary keys in their respective tables
all combinations of one_id and two_id in TABLE_THREE are guaranteed to be unique, so there will be either zero or one set of records correlating some exact collection of one_id values with the same two_id.
suppose TABLE_ONE has records with the following values for one_id:
1,3,5,7
suppose TABLE_TWO has records with the following values for two_id:
2,4,6
suppose TABLE_THREE has records with the following pairs of values for one_id,two_id:
1,2
3,2
3,4
5,4
1,6
3,6
5,6
7,6
finally, suppose I need to find the value of two_id (if there is one) that EXACTLY correlates with exactly two values of one_id: 3 and 5.
select two_id
from table_three
where one_id in (3,5)
group by two_id
won't work:
* it matches 2, because a match with only the 3,2 record is enough to satisfy the condition
* it matches 4 because it should, but...
* it also matches 6, even though 6 has more records.
in other words, I need a stronger condition than "in" that requires the collection of records in each two_id group match the specified collection EXACTLY (but ideally, in an order-agnostic way, so a match for 3 and 5 would be the same as a match for 5 and 3).
to give a fictional, but illustrative example...
select two_id
from table_three
where one_id IS (3,5)
group by two_id

First a little set up
SQL> SELECT two_id FROM table_three where one_id = 3;
    TWO_ID
         3
     13545
SQL> INSERT INTO table_three VALUES(5,13545);
1 row created.
SQL> commit;
Commit complete.
SQL> SELECT COUNT(*) FROM table_three;
  COUNT(*)
    108376
SQL> SELECT COUNT(*) FROM (SELECT DISTINCT one_id, two_id FROM table_three);
  COUNT(*)
    108376Now, I have 108,376 distinct rows, and only two_id 13545 has both 3 and 5 in one_id.
Andrew's version, which can be simplified (Andrew: You're not ususally so vebose :-) )
SQL> SELECT two_id
  2  FROM table_three
  3  WHERE one_id IN (3,5)
  4  GROUP BY two_id
  5  HAVING COUNT(*) = 2;
Statistics
          0  recursive calls
          0  db block gets
        113  consistent gets
          0  physical reads
          0  redo size
        491  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          1  rows processedNow, 270432:
SQL> SELECT tt1.two_id
  2  FROM   table_three tt1, table_three tt2
  3  WHERE  tt1.two_id = tt2.two_id AND
  4         tt1.one_id = 3 AND
  5         tt2.one_id = 5 AND
  6         NOT EXISTS (SELECT NULL
  7                     FROM   table_three   tt3
  8                     WHERE  tt3.two_id  = tt1.two_id AND
  9                            tt3.one_id <> tt1.one_id AND
10                            tt3.one_id <> tt2.one_id);
Statistics
          0  recursive calls
          0  db block gets
        242  consistent gets
          0  physical reads
          0  redo size
        274  bytes sent via SQL*Net to client
        456  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          0 rows processed Note 0 rows processed.
Now David's first query:
SQL> SELECT two_id
  2  FROM table_three
  3  GROUP BY two_id
  4  HAVING COUNT(*)    = 2 And
  5         MAX(one_id) = 5 And
  6         MIN(one_id) = 3;
Statistics
          0  recursive calls
          0  db block gets
        113  consistent gets
          0  physical reads
          0  redo size
        274  bytes sent via SQL*Net to client
        456  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          0 rows processedAs efficient as Andrew's, but again, no rows processed.
David's Non-set based method:
SQL> SELECT two_id
  2  FROM table_three t3
  3  WHERE one_id = 3 And
  4        EXISTS (SELECT 1 FROM table_three t3_x
  5                WHERE  t3_x.two_id = t3.two_id And
  6                       t3_x.one_id = 5) And
  7        NOT EXISTS (SELECT 1 FROM table_three t3_x
  8                    WHERE  t3_x.two_id = t3.two_id And
  9                           t3_x.one_id NOT IN (3,5));
Statistics
          0  recursive calls
          0  db block gets
        265  consistent gets
          0  physical reads
          0  redo size
        274  bytes sent via SQL*Net to client
        456  bytes received via SQL*Net from client
          1  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
          0 rows processedNow, my alternative:
SQL> SELECT two_id FROM table_three
  2  WHERE one_id = 3
  3  INTERSECT
  4  SELECT two_id FROM table_three
  5  WHERE one_id = 5;
Statistics
          0  recursive calls
          0  db block gets
        226  consistent gets
          0  physical reads
          0  redo size
        491  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          1  rows processedSo, not as efficient as Andrew's, but at least correct. Does an Index help Andrew or me?
SQL> CREATE INDEX t3_one_id ON table_three(one_id);
Index created.Now, Andrew, then me.
SQL> SELECT two_id
  2  FROM table_three
  3  WHERE one_id IN (3,5)
  4  GROUP BY two_id
  5  HAVING COUNT(*) = 2;
Statistics
          0  recursive calls
          0  db block gets
          9  consistent gets
          0  physical reads
          0  redo size
        491  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
          1  rows processed
SQL> SELECT two_id FROM table_three
  2  WHERE one_id = 3
  3  INTERSECT
  4  SELECT two_id FROM table_three
  5  WHERE one_id = 5;
Statistics
          0  recursive calls
          0  db block gets
          9  consistent gets
          0  physical reads
          0  redo size
        491  bytes sent via SQL*Net to client
        651  bytes received via SQL*Net from client
          2  SQL*Net roundtrips to/from client
          2  sorts (memory)
          0  sorts (disk)
          1  rows processedWith an index, equivalent gets, but I still do two sorts.
John

Similar Messages

  • What is the best way to get the minimum or maximum value from an Array of numbers?

    Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]
    What is the best way to find the minimum or maximum value in
    that Array?
    Right now, to get the maximum, I am looping through the
    Array, and resetting a variable to the value if it is greater than
    the existing value:

    Here's other approaches, the cookbook is your friend:
    http://digitalmedia.oreilly.com/pub/a/oreilly/digitalmedia/helpcenter/actionscript30cookbo ok/chapter5.html?page=7
    enjoy.

  • Best way to select distinct values based on another column?

    I have a table with three columns: id (NUMBER), data_dt (DATE), and data_value (NUMBER).
    There is a primary key on id and data_dt.
    I want to select the record with the latest data_dt for each unique id.
    What is the best way to do this?
    I have three different methods, but there may be something I am missing.
    First:
    SELECT *
    FROM
      SELECT id, data_dt, data_value,
             FIRST_VALUE(data_dt)
             OVER (PARTITION BY id ORDER BY data_dt DESC) AS last_data_dt
      FROM the_table
    WHERE data_dt = last_data_dt;(I use ORDER BY...DESC instead of just ORDER BY so I don't need the ROWS BETWEEN clause)
    Second:
    SELECT t1.*
    FROM the_table t1
    JOIN
      SELECT id, MAX(data_dt) AS last_data_dt
      FROM the_table
      GROUP BY id
    ) t2 ON (t2.id = t1.id AND t2.data_dt = t1.data_dt);Third:
    SELECT t1.*
    FROM the_table t1
    WHERE t1.data_dt =
      SELECT MAX(t2.data_dt)
      FROM the_table t2
      WHERE t2.id = t1.id
    );-- Don

    Hi,
    There are more possible scenario's, for example:
    select t1.*
    from   the_table t1
    where not exists ( select null
                       from   the_table t2
                       and    t2.data_dt > t1.data_dt
    What is the best way to do this?Only you can tell:
    Test all scenario's, check the execution plans, set timing on and pick the best/fastest one ;-)
    If it's not clear, please post the execution plans here.

  • Best way to select BOTH notes and midi CC?

    Hello everyone,
    I'm trying to figure out the quickest, most efficient way to select and move both notes and MIDI CC's at the same time in the matrix editor w/ hyperview. The only way I've been able to accomplish this is to shift-drag around both parts, but this takes time time as you have to do it TWICE; once for the notes and once for the midi cc's. Unfortunately "select all" or "select within locators" does not select midi cc's.
    What is the best way to deal with midi cc's? I wish there was some way to select and "lock" them to midi notes and when you drag the notes, it drags the midi cc as well, similar to how FCP locks audio and video together. Do other programs allow this functionality?
    Thanks once again for any help/tips you can provide!

    Functions > Include Non-note MIDI Events, but unfortunately there is no key command for it.
    I prefer to have a screenset with an Event List open, so I can Command-~ to the event list, Command-A, and then drag in the Matrix. Or double click the fist note in the Event List and enter a new Bar# for its position. Or Command-C and Command-V, then enter a new number for a copy...
    ...you get the idea.

  • What is the best way of selecting 99 colums from a table with 100 colums?

    Hi All,
    Suppose in a table T, I have 100 colums .I want to select 99 columns.So what is the best way to do the same?
    Anyone Help!
    Thanx in advance.
    Piyush

    Try this
    SQL> ed
    Wrote file afiedt.buf
      1  select column_name ||',
      2  ' from user_tab_columns
      3  where
      4     table_name = 'EMP'
      5*    and column_name not like 'EMPNO'
    SQL> /
    COLUMN_NAME||','
    ENAME,
    JOB,
    MGR,
    HIREDATE,
    SAL,
    COMM,
    DEPTNO,
    7 rows selected.
    SQL>

  • What's the best way to transfer itunes music collection from pc to pc

    So after some weeks of working at it, I finally have my itunes collection on my Dell about where I wanted, stray tracks have been returned to their proper home, genres are properly assigned, album art located and placed where it belongs and duplicates have been eliminated and so forth.  I thought the time had come to transfer a copy of this magnus opus to my surface pro 2.  Itunes loads just fine to SP 2 desktop (since the SP is both a full function PC as well as a tablet the absence of an itunes app for the SP is of no significance). 
    I used a flash drive to transfer the files located under itunes.  What I discovered was much of the album art did not transfer and perhaps a quarter of the music didn't transfer either.  I can't explain the former, but the latter appears to be related to music I purchased through Amazon which is stored elsewhere (although Itunes had no difficulty finding it on my Dell and I had no trouble working with it to get the various tasks completed that are mentioned above).  I thought I could just perhaps copy the amazon folder to SP 2 music folder but that didn't work either.
    So the thought occurs to me that I am making entirely too much work of this.  There has to be a relatively simple way to transfer the Itunes collection to another Itunes program, also running on a pc.  What easy thing am I missing, yet again?  thanks!

    There is more to an iTunes library than the purchases alone.
    There is more to an iTunes library than the media files alone.
    The library files and album artwork folders contain other data that should be copied. The iTunes database may hold the only reference for artwork for some files, and will be the only place holding metadata for any files in .wav format. It is also where playlists, ratings, play counts and other data not stored in tags resides.
    In particular each library has a unique ID, copying the media alone doesn't transfer this, and syncing a device to a library with a different ID can cause data loss.
    Copying the entire iTunes folder is the key, but even then extra care may be needed if the library is in the wrong shape, e.g. files stored outside the media folder, or the media folder not stored inside the main iTunes folder.
    The vector used for the transfer, flash drive, external hard drive or network, can be selected according to availability and suitability. In the case of the Surface Pro 2 we're unlikely to be discussing a large library, but you should be aware that people have libraries larger than any available flash drive.
    One transfer over a network may be faster, or more convenient, than copying files to a secondary drive at the source computer and then copying again from that drive to the target.
    tt2

  • What is the best way to delete folders and collections from Library?

    I have approximately 500 photographs in folders and collections. Want to delete them and start over. What is the best way to go back to Lightroom 5 cc as it was when initially downloaded?
    Using Mac running Maverick.
    Thanks for your help

    File>New Catalog and start over.
    The 500 images will stay put where they are and you can choose to import them again into the pristine catalog.

  • Best way to pre-populate material variable with values for users

    Hi,  I have a requirement to prepopulate a material variable with about 5 materials and that is the materials that will default when the query is called.  The users would also need the ability to change those values.
    My thought is to create a User-exit variable that derives the values from a user maintained table (infoobject). 
    Does anyone else have any suggestions or ideas on the best way to handle this?

    I don't know if there is a best solution...
    Infoobject
    With this option you have to create a new infoobject (ZMATERIAL) without attribute (you need only a list material codes) and then to set the authorization profile for the user in order to manage the content.
    The creation of an infoobject corresponds to a table creation, but you don't need any other specific options that belong to the infooject (as technical object)...
    Table
    With this option you have to create a Z table with only one field and then to allow the maintenance of the table by SM30....
    In the ending, if you want to be a purist use the table, otherwise use an infoobject (but there are no significant differences !
    Bye,
    Roberto

  • What is the best way to update /101 Total Gross YTD values within CRT

    Hello - Can someone please suggest the best way that I can update the current /101 YTD values within the CRT?  We had a conversion effort take place earlier in the year that did not accumulate the amounts of one particular wage type to the /101 bucket.  The wage type itself is currently in the CRT with the appropriate accumulators set up correctly but the /101 YTD values are too low due to the missing amounts.  Any suggestions would be greatly appreciated.
    Thanks!

    Hello Kristy,
    Did you try RPUCRT00? This program is for Recreation of Payroll Cumulation tables and might help in this case.
    Hopefully this information helps.
    Kind regards,
    Graziela Dondoni

  • Best way to select several mysql table rows at random?

    What is the best and quickest way to have one form button select multiple rows from a table with complete randomness?
    Can you also offer some explanation (or link to a good tutorial)- I am a beginner in myql and php.
    thanks
    p.s. the id column in my table is auto incrementing and has some gaps (due to deletions of records). I do not want any of those gaps to be chosen at random (can they?).

    What do you have so far? How many rows will your table have and how many do you want to randomize? To produce random result without filter will put a strain on your server, especially if you have a lot of rows and you get a lot of server requests (pageloads). To randomize the results you basically have to recreate the table dynamically then output the result as an array. Again, this will put a huge load on your server. This may sound silly and ridiculously obvious, but have you tried searching the obvious term on google for MySQL random? There are millions of articles that describe the subject. Many first page results will show you exactly what you need to do. Try searching first then if you have trouble ask here, referencing the article you followed by first searching google.
    best,
    Shocker

  • Best way to sync Lightroom 5 Collections to IOS8 IPad and IPhone (offline available)

    Hello,
    I have looked at several options but have not found an elegant solution yet to a problem that many users must have.
    Problem
    I have a lot of Collections in my Lightroom Library and would like to make them available to my iphone and ipad to show them (offline).
    Requirements:
    The Collection "folders" should be reflected with the same name as Albums on the iphone/ipad.
    They should be available offline (ideally selecting which to synchronise offline and which only on a cloud".
    The quality should be good jpg but not highest printing jpg for ipad display.
    I would like to have a solution using a cloud (i.e. publishing service of lightroom) because i dont want to connect and sync the ipad and the iphone everytime there are changes to the collections. Internet is fast enough to sync that (upload to a cloud and download)
    I dont need to share them with others, but could be an additional benefit but ONLY if privacy is assured. I dont want to make them available to everyone.
    Possible tools i could use that i have already:
    The pictures on ipad quality will take up a few GB (10 maybe) so that i need some storage facility on a cloud i guess, I have dropbox, flick and more limited Icloud for that in theory.
    I have a plug in Photoupload for Dropbox where i sync all my collections in printable quality. 
    I have a Flickr account - which i am not really familiar in using with lightroom.
    I have an icloud account which i dont sync because i dont use iphoto.
    I have a feeling that Flickr should offer this, but have so far not been able to figure out how to do it efficiently. I would like to limit monthly costs for this system, but if it works great, I could also consider it of course. I would be interested in hearing your solutions to this issue and ideally some link or how to do it manuals.
    Many thanks for your help!

    Thank you for your quick reply 99jon
    I have looked at Lightroom Mobile a bit. To stay within one system is always helpful for syncing. And LR-Mobile looks like the natural choice indeed but 120USD per year is slightly steep considering the availability of other clouds for more competitive prices, or like dropbox for multipurpose services.
    Also i do not need to edit the pictures on ipad or iphone
    I do have enough memory for either compressed jpgs or in lightroom mobile smart previews. (so no w-lan hdd needed) on the mobile devices
    Do you happen to know a tutorial or video on flickr publishing for lightroom in the sense that i would be looking for.
    Is there a way to combine the workflow of sending the high-res jpgs of a collection to the flickr and the smartpreview/compressed jgp to Iphone/Ipad albums?
    many thanks again

  • Is there a way to select matching pixels on 2 different layers?

    Hey there,
    I've been wondering about this a long time now and can't seem to figure it out. I hope u guys can help me crack this.
    If I shoot 2 different portraits (of 2 different people), against the same background (a complex one not a backdrop), using a locked frame on a tripod, giving me the same exact background in both pictures, with only the portraits changing.
    If I then take these 2 pictures, and create layers out of them in the same Photoshop document, and align them perfectly on top of each other.
    Is there a way (action, plugin, script, etc...) to select the pixels that did not change between the 2 layers? In other words, the pixels that create the background of both pictures?
    And would it make it easier if I shoot the background alone, and then the portraits, and then follow the same steps?
    I'm posting this, and crossing my fingers.
    Thanks,
    Pierre.

    Changing the blend mode of the upper layer to Difference, will show identical pixels as full black.  To make a selection, you'd need to produce a copy merged layer (Shift Ctrl Alt e) and you could select the full black pixels by simple a method as using the magic wand with a low tolerance value.  In fact a tolerance of '1' will select all the identical pixels, but tiny variations in lighting etc. may need a higher tolerance.
    Save the selection, turn off the copy merged layer, change the blend mode of the upper layer back to normal > And you are good to go.
    I am wondering how you intend using this though, and what sort of end result you are hoping for?  Give it a try and come back to us if it doesn't work out

  • Best way to select a record to display in the report

    Hi,
    I am helping a customer get a report (V11) working in the Visual Studio 2008 viewer.
    The report, where they have linked all the tables from the database,  has a paramater called 'jobNo'.
    The record select expert then uses the param to select the required job. ({uv_JobDetails.JobNumText} = {?JobNo})
    My question is how do I from my ASP.net (VB.net code) set this parameter, and then refresh the report to show the correct data matching the parameter jobNo.
    Thanks

    Hi,
    Try with this:  
    ReportDocument boreportdocument = new ReportDocument();
    boreportdocument.Load(Server.MapPath("Decreteparam.rpt"));
    string recordselection = "{Customer.Country} = " + "{?My Parameter}";
    boreportdocument.RecordSelectionFormula = recordselection;
    CrystalReportViewer1.ReportSource = boreportdocument;
    or //Set parameter value like this
    boreportdocument.SetParameterValue("My Parameter", "USA");
    For Range Parameter:
    boreportdocument.Load(Server.MapPath("RangeParam.rpt"));
    CrystalReportViewer1.ReportSource = boreportdocument;
    boparamfields = CrystalReportViewer1.ParameterFieldInfo;
    //setting the start and end values
    boparamField = boparamfields["SalesRange"];
    boparamValues = boparamField.CurrentValues;
    boparamrangevalue.EndValue = "300";
    boparamrangevalue.LowerBoundType = RangeBoundType.BoundInclusive;
    boparamrangevalue.StartValue = "27";
    boparamrangevalue.UpperBoundType = RangeBoundType.BoundInclusive;
    //Adding Range values to parameter field
    boparamValues.Add(boparamrangevalue);
    You can get sample codes from [here|https://boc.sdn.sap.com/codesamples]
    Have a look to our [Dev Library|https://www.sdn.sap.com/irj/boc/sdklibrary ]
    Regards,
    Shweta

  • Looking for best way to select a list of components

    I have a button that checks user input to make sure it's the right format.
    I want this button to extend a debugger type window... I was wondering if there was a class that someone could recommend to me.
    Inside the window being extended I want there to be a table with columns labeled "Error Message", "Input", "At", "ReplaceWith". The first three will be disabled text fields, but the fourth one i want to hold a textfield with a button... Any recommendations as to how to most efficiently implement a selectable row of components would be greatly appreciated. Thanks.

    i could always just fake a table via a class
    extending a JPanel with all the data in it & just
    have an array of this class & throw those into a
    bigger JPanel... if anyone knows of a better, cleaner
    way to do this, please let me know.Possibly better to use JDialog with a JTable rather than JPanel since my guess is that you want to present this information in a modal way (though I could be wrong).

  • Best way to import large CD collection to external NAS drive using iTunes

    I am planning to re-import a large CD collection to an external NAS drive with iTunes. Previously I imported using a WAV encoder, but now realize that none of the music was tagged and attempts using a tag from file name script proved unsuccessful.
    Can anyone advise me on the best method and codic to do this with iTunes? I was planning to use either AAC or MP3 set at 256 or 320kbps. Both of these encoders, I am being told, will hold the ID3 tag. Any other recommendations on this process is welcomed.
    Also, once I have the music imported to the network drive, how do I get the itune library to be recognized on another computer on the network (not the computer that was used to import)?

    Jaydawk wrote:
    Can anyone advise me on the best method and codic to do this with iTunes? I was planning to use either AAC or MP3 set at 256 or 320kbps. Both of these encoders, I am being told, will hold the ID3 tag.
    All of the iTunes compatible formats will accept tags, except for WAV. Most people nowadays use either AAC or MP3 at 256 kb/s. But if your ears and your audio setup require the extra fidelity of a lossless format, go with Apple Lossless or AIFF.
    Before you start ripping, go to Edit > Preferences > Advanced, and set the iTunes Media folder location to the NAS. Then any files that you rip from CD will go straight to the NAS.
    Also, once I have the music imported to the network drive, how do I get the itune library to be recognized on another computer on the network (not the computer that was used to import)?
    iTunes does not have any folder watching capability. Once the files are on the NAS, you can manually go to another computer's iTunes to add them (File > Add Folder to library) or you can get 3rd party folder watching software such as iTunes Folder Watch.

Maybe you are looking for