Can you check for data in one table or another but not both in one query?

I have a situation where I need to link two tables together but the data may be in another (archive) table or different records are in both but I want the latest record from either table:
ACCOUNT
AccountID     Name   
123               John Doe
124               Jane Donaldson           
125               Harold Douglas    
MARKETER_ACCOUNT
Key     AccountID     Marketer    StartDate     EndDate
1001     123               10526          8/3/2008     9/27/2009
1017     123               10987          9/28/2009     12/31/4712    (high date ~ which means currently with this marketer)
1023     124               10541          12/03/2010     12/31/4712
ARCHIVE
Key     AccountID     Marketer    StartDate     EndDate
1015     124               10526          8/3/2008     12/02/2010
1033     125               10987         01/01/2011     01/31/2012  
So my query needs to return the following:
123     John Doe                        10526     8/3/2008     9/27/2009
124     Jane Donaldson             10541     12/03/2010     12/31/4712     (this is the later of the two records for this account between archive and marketer_account tables)
125     Harold Douglas               10987          01/01/2011     01/31/2012     (he is only in archive, so get this record)
I'm unsure how to proceed in one query.  Note that I am reading in possibly multiple accounts at a time and returning a collection back to .net
open CURSOR_ACCT
          select AccountID
          from
                 ACCOUNT A,
                 MARKETER_ACCOUNT M,
                 ARCHIVE R
           where A.AccountID = nvl((select max(M.EndDate) from Marketer_account M2
                                                where M2.AccountID = A.AccountID),
                                                  (select max(R.EndDate) from Archive R2
                                                where R2.AccountID = A.AccountID)
               and upper(A.Name) like parameter || '%'
<can you do a NVL like this?   probably not...   I want to be able to get the MAX record for that account off the MarketerACcount table OR the max record for that account off the Archive table, but not both>
(parameter could be "DO", so I return all names starting with DO...)

if I understand your description I would assume that for John Dow we would expect the second row from marketer_account  ("high date ~ which means currently with this marketer"). Here is a solution with analytic functions:
drop table account;
drop table marketer_account;
drop table marketer_account_archive;
create table account (
    id number
  , name varchar2(20)
insert into account values (123, 'John Doe');
insert into account values (124, 'Jane Donaldson');
insert into account values (125, 'Harold Douglas');
create table marketer_account (
    key number
  , AccountId number
  , MktKey number
  , FromDt date
  , ToDate date
insert into marketer_account values (1001, 123, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('27.09.2009', 'dd.mm.yyyy'));
insert into marketer_account values (1017, 123, 10987, to_date('28.09.2009', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
insert into marketer_account values (1023, 124, 10541, to_date('03.12.2010', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
create table marketer_account_archive (
    key number
  , AccountId number
  , MktKey number
  , FromDt date
  , ToDate date
insert into marketer_account_archive values (1015, 124, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('02.12.2010', 'dd.mm.yyyy'));
insert into marketer_account_archive values (1033, 125, 10987, to_date('01.01.2011', 'dd.mm.yyyy'), to_date('31.01.2012', 'dd.mm.yyyy'));
select key, AccountId, MktKey, FromDt, ToDate
     , max(FromDt) over(partition by AccountId) max_FromDt
  from marketer_account
union all
select key, AccountId, MktKey, FromDt, ToDate
     , max(FromDt) over(partition by AccountId) max_FromDt
  from marketer_account_archive;
with
basedata as (
select key, AccountId, MktKey, FromDt, ToDate
  from marketer_account
union all
select key, AccountId, MktKey, FromDt, ToDate
  from marketer_account_archive
basedata_with_max_intervals as (
select key, AccountId, MktKey, FromDt, ToDate
     , row_number() over(partition by AccountId order by FromDt desc) FromDt_Rank
  from basedata
filtered_basedata as (
select key, AccountId, MktKey, FromDt, ToDate from basedata_with_max_intervals where FromDt_Rank = 1
select a.id
     , a.name
     , b.MktKey
     , b.FromDt
     , b.ToDate
  from account a
  join filtered_basedata b
    on (a.id = b.AccountId)
ID NAME                     MKTKEY FROMDT     TODATE
123 John Doe                  10987 28.09.2009 31.12.4712
124 Jane Donaldson            10541 03.12.2010 31.12.4712
125 Harold Douglas            10987 01.01.2011 31.01.2012
If your tables are big it could be necessary to do the filtering (according to your condition) in an early step (the first CTE).
Regards
Martin

Similar Messages

  • Copying data from one table to another, but not duplicate

    Good afternoon!
    I am new to Oracle SQL, I have a difficulty.
    I have a script that copies or add another table with data from another table.
    If the table already has 01 "Registry 01" when you make a copy of the data in table 02, can not duplicate the "Registry 01" again.
    As the table already exists since the beginning of the year before last and duplicate information, I can not apply the UNIQUE constraint because of the error. I have to make this change from now.
    How to perform this validation so that no duplicate data?
    DECLARE
    w_cont NUMBER;
    CURSOR c_simpro IS
    SELECT sc.cd_simpro,
    sc.ds_produto,
    sp.qt_embalagem,
    MAX(sp.dt_vigencia)
    FROM simpro_cadastro sc,
    simpro_preco sp
    WHERE sc.cd_simpro = sp.cd_simpro
    GROUP BY sc.cd_simpro,
    sc.ds_produto,
    sp.qt_embalagem;
    BEGIN
    FOR r_simpro IN c_simpro LOOP
    w_cont := 0;
    SELECT COUNT(1)
    INTO w_cont
    FROM pls_material pm
    WHERE pm.cd_material_ops = r_simpro.cd_simpro;
    IF w_cont = 0 THEN
    INSERT INTO pls_material(nr_sequencia,
    dt_atualizacao,
    nm_usuario,
    dt_atualizacao_nrec,
    nm_usuario_nrec,
    ie_tipo_despesa,
    cd_estabelecimento,
    nr_seq_estrut_mat,
    cd_simpro,
    ds_material,
    ie_situacao,
    ds_material_sem_acento,
    dt_inclusao,
    cd_material_ops_orig,
    cd_unidade_medida,
    cd_material_ops,
    qt_conversao_simpro)
    VALUES(pls_material_seq.nextval,
    SYSDATE,
    'ES-SIMPRO',
    SYSDATE,
    'ES-SIMPRO',
    3,
    1,
    3,
    r_simpro.cd_simpro,
    r_simpro.ds_PRODUTO,
    'A',
    r_simpro.ds_PRODUTO,
    SYSDATE,
    r_simpro.cd_simpro,
    'un',
    TRIM(to_char(r_simpro.cd_simpro,'0000099999')),
    r_simpro.qt_embalagem);
    COMMIT;
    END IF;
    IF w_cont > 0 THEN
    UPDATE pls_material p
    SET p.qt_conversao_simpro = r_simpro.qt_embalagem,
    p.dt_atualizacao = SYSDATE
    WHERE p.cd_simpro = r_simpro.cd_simpro;
    COMMIT;
    END IF;
    END LOOP;
    END;
    Edited by: 983464 on 22/01/2013 10:30

    Hi,
    in addition to what Marwin has already said, I suggest you to post CREATE TABLE and INSERT statements (as mentioned in the FAQ).
    The error you are getting from MERGE command is because you need a way to uniquely identify within the table. So it's is important to know also if your table has a primary key/unique index so the keys could to be used in the MERGE command.
    Additionally when you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Can you check the date of a iphone photo

    can you check the date of an iphone photo

    Snow? what is that...
    You definitely want to check out these apps:
    wine
    https://itunes.apple.com/au/app/the-wine-regions-of-victoria/id407627657?mt=8
    nature
    https://itunes.apple.com/au/app/field-guide-to-victorian-fauna/id423945031?mt=8
    Events
    https://itunes.apple.com/au/app/vicevents/id468981322?mt=8

  • How do I set upmy Imac to allow using both my computer speakers and a Bose SoundLink system as outputs at the same time.  I can use one or the other, but not both.

    how do I set up my Imac to allow using both my computer speakers and a Bose SoundLink system as outputs at the same time.  I can use one or the other, but not both.  From systems Preferences I must select one or the other.  I want both to work all the time.

    Hi,
    I would recommend you to use 0FI_AP_4 rather using both, particularly for many reasons -
    1. DS: 0FI_AP_4  replaces DataSource 0FI_AP_3 and still uses the same extraction structure. For more details refer to the OSS note 410797.
    2. You can run the 0FI_AP_4 independent of any other FI datasources like 0FI_AR_4 and 0FI_GL_4 or even 0FI_GL_14. For more details refer to the OSS note: 551044.
    3. Map the 0FI_AP_4 to DSO: 0FIAP_O03 (or create a Z one as per your requirement).
    4. Load the same to a InfoCube (0FIAP_C03).
    Hope this helps.
    Thanks.
    Nazeer

  • How do I adjust the page orientation in Pages?  I want to keep the pages above the section break as portrait, and the ones below I want to change into landscape.  Is this possible?  I can only get it to be one or the other but not both.

    I want to keep the pages above the section break as portrait, and the ones below I want to change into landscape.  Is this possible?  I can only get it to be one or the other but not both.

    The work around is to do two documents, one in portrait format and one in landscape format. When finished export to Pdf. open in Preview by select both files and use Cmd + O or doubleclick. You can now in Previews thumbnail column the pages from one document into the other and then save.
    If you have created only one with i.e. all pages in portrait format but with the content for the landscape pages rotated on the pages, you can rotate the pages in Preview. Two ways to get the same result.

  • How do I create both endnotes and footnotes in same doc in Pages? I have iWork 2008. I understand how to create one or the other, but not both.

    How do I create both endnotes and footnotes in same doc in Pages? I have iWork 2008. I understand how to create one or the other, but not both.

    You have to select one or the other.
    Try making two documents and see if you can merge the .pdfs, but their will be problems with page flow, making the pages shift. Can't see it working really.
    Pages is not the only solution out there or the best for most jobs (let alone the safest). Try Word for Mac, LibreOffice (free) or any App that has the features you need.
    Peter

  • After installing Lion, the Software Update "can't check for updates because of a network problem.But I've no network problem. My internet is working properly. could you help me?

    After installing Lion the Software Update "can't check for updates because of a network problem". But I've no network problem. My internet is working properly. Could yoy help me?

    Hi All
    Same problem this morning but now resoloved.
    Update require using the following url  support.apple.com/kb/DL1437 update for lion 10.7.1
    updates now work with this update
    Hope this helps
    Thanks

  • Touch Events: How can I check for a button being pressed while another button is being held down?

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

    Hello,
    I'm trying to check for a button being pressed while another is down through Touch.  In my case, I' m making a game and I need for a button to make the character jump.  However, when I hold down right, I notice that the jump button becomes somewhat unresponsive and I have to press it twice or more to get it to trigger, as opposed to just pressing the jump button by itself with nothing held down which works fine.  I'm testing this on my Motorola Droid 2.
    Here is some of my code that demonstrates text instead of my character moving around:
    package  {
         import flash.events.TouchEvent;
         import flash.ui.Multitouch;
         import flash.ui.MultitouchInputMode;
         public class Document extends MovieClip {
               Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
               private var controls:BottomBar;
               private var debugText:String;
               public function Document() {
                    addIngameGUI();
               private function addIngameGUI(){
                    controls = new BottomBar();
                    controls.y = stage.stageHeight - controls.height;
                    addChild(controls);
                    controls.aBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.bBtn.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.leftArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
                    controls.rightArrow.addEventListener(TouchEvent.TOUCH_BEGIN, testBtns);
             private function testBtns(event:TouchEvent){
                   debugText.text = event.target.name;
    What am I doing wrong?  Is there a better approach?
    Thank you in advance.

  • Mac mini server has suddenly stopped seeing one or the other bluetooth devices! Batteries have been changed and they will connect to an older Mac mini. Server will now only see one or the other but not both.

    My Mac mini server has suddenly stopped seeing one or the other bluetooth devices, either the wireless keyboard or the mouse( both apple products) have tried new batteries, at first it was the mouse that stopped responding, but upon rebooting the computer now the keyboard will not respond and the mouse works. Both work fine on an older Mac mini that I hooked back up to check.

    There is absolutely no reason why they should not bothe be able to connect to your WiFi network. The easiest place to start would be to reboot your router. Unplug it for about 30 seconds and then plug it back in again. I would also restart both the iPad and the iPhone.

  • I believe for the year I have not been using photoshop photography but something else so I never really used it or photoshop photography ..can you check for me

    now that I just re-newed my photoshop photography ....I have not been using that for some reason I have been using something else. they had changed me a couple
    of times last year from one thing to another ...so I never go photoshop photography downloaded. I used the other one very little because I wasn't sure I should...gee
    I hope that makes sense.
    I need to download photoshop photography.
    Sherri nicholas

    You need to get the owner's manual for your Ford's bluetooth system to see how to put your system into discovery mode for the iPhone as well as the appropriate steps to take. 
    In addition, you should see if the iPhone is supported.

  • How many apps can you have for sale with a CC Complete membership? (Not Pro or Enterprise)

    I have the CC complete membership (£46 p/m) I was under the impression I could only have 1 app for sale on the Apple store with this. But I've re-read the guidelines and it says I can have unlimited apps. I've been working on an ipad app, which has ended up exceeding the 100mb limit (I think this limit is new, too) But my app could be divided up logically into 2 or 3 apps for individual publication, so long as each has the $99 fee paid. Do my conclusions sound right, or have I missed something?

    >for sale on the Apple store
    This is Adobe... I think you need to ask Apple about their store policies

  • Can I use Migration Assistant to Copy files from one mac to another, but not delete the original files off of the original Mac?

    I just purchased a new Macbook Pro Retina, and I have an old Macbook Pro w/o Retina and wish to use migration assistant. I still want to use the older Macbook Pro and keep all the files on it, but copy them and also put them on my new Macbook. What I'm trying to say is, can I use migration assistant to move files to a new Mac, while keeping the files on the old computer?

    You can omit some broad categories, but you can't pick and choose individual items.
    See Using Setup Assistant on Mountain Lion or Lion (preferred method), or the similar Using Migration Assistant on Mountain Lion or Lion for the gory details.

  • How can I record a microphone and software instrument at the same time in Garageband 10.0.1?  It seems I can record one or the other, but not both at the same time?

    I am trying to record a vocal mic and a keyboard (using a software instrument) at the same time using Garageband 10.0.1.  It seems that I can't record the mic input and the software instrument at the same time.  I can record the mic input by itself, and I can record the software instrument by itself (if I don't have a mic input track created), but I can't record them together.
    It seems like this should be an obvious thing to be able to do, but I can't figure out how to make it work.
    Can someone help?
    Thanks,
    Kurt

    Kurt1997 wrote:
    I am trying to record a vocal mic and a keyboard (using a software instrument) at the same time using Garageband 10.0.1.
    you need to "record enable" both tracks:
    http://www.bulletsandbones.com/GB/GBFAQ.html#multitrackrecordinggbv10
    This FAQ entry offers a Minute GarageBand video tutorial
    (Let the page FULLY load. The link to your answer is at the top of your screen)

  • How to copy data from one table to another (in other database)

    Hi. I would like to copy all rows from one table to another (and not use BC4J). Tables can be in various databases. I have already 2 connections and I am able to browse source table using
    ResultSet rset = stmt.executeQuery("select ...");
    But I would not like to create special insert statement for every row . There will be problems with date formats etc and it will be slow. Can I use retrieved ResultSet somehow ? Maybe with method insertRow, but how, if ResultSet is based on select statement and want to insert into target table? Please point me in the right direction. Thanks.

    No tools please, it must be common solution. We suceeded in converting our BC4J aplication to PostgreSQL, the MSSQL will be next. So we want to write simple aplication, which could transfer data from our tables between these 3 servers.

  • I purchase Adobe Creative Suite 5.5 Web Premium and I did not get Illustrator in my package. Can you check on that issue please!

    I purchase Adobe Creative Suite 5.5 Web Premium and I did not get Illustrator in my package. Can you check on that issue please!

    Web Premium does not contain AI.
    Mylenium

Maybe you are looking for

  • Background image for JPanel

    I was to come here and "search" for examples on this but i havnt found any so im jsut going to post it: How do i set an image to be the background of a JPanel? setBackground(image); doesnt work... i was toal something about paintComponent() but i tri

  • LG App Uninstall "Recycle Bin" Sound and SMS Pop Up Missing

    I have recently noticed 2 things: 1:  When an app is uninstalled via drag and drop to the notification bar, the "crumpled paper" Windows PC Recycle Bin sound is now gone. 2:  No matter what I check, stock SMS will no longer Pop Up on the display.  No

  • Java on Linux

    Hey, I downloaded the java VM for my Red hat Linux OS i got on my box. I thought it bought time i got it. Well, i also wanted to test my game on the java VM for Linux, as i have tested it on the Windows Java VM and it works perfectly. However with th

  • I have two fields and I would like the 2nd field to display the word "Error" if the number is smalle

    I have two fields and I would like the 2nd field to display the word "Error" if the number is smaller than the number in field 1. can any one help?

  • Wireless problems in 'high' traffic areas

    When using wifi anywhere (uni, cafe), I can obtain a full connection when traffic is low. As more people start to use their computers in the area around me, my wireless starts to dwindle and then disconnects. Is this a common problem, and is it treat