How to join these two queries

Hi experts,
I need to join two queries but not sure how:
select id from test_table1;
select *
  from table(f_function(null
                       ,null
                       ,1 -- the id
                       ,sysdate);One query has IDs needed to run the second query. Is there a way to join those two?
The result should be all columns from test_table1 + all columns from f_function.
Best regards,
Igor
Edited by: Igor S. on Mar 8, 2013 5:18 AM

Hi,
Igor S. wrote:
select  *
from  test_table1,
table(
f_function(
null,
null,
id,
sysdate
select  *
from  test_table1,
table(
f_function(
null,
null,
id,
sysdate
) xyz
where test_table1.id = xyz.id
/So these two queries are the same?Try it and see.
You'll find that the 2nd one produces an error. But if you change it to
select  *
  from  test_table1,
        table(
              f_function(
                         null,
                         null,
                         id,
                         sysdate
                        )      -- No alias here
             ) xyz             -- Alias here, instead
where test_table1.id = xyz.id
/Then, assuming f_function produces a column called id, it will work.
Whether it produces the same results or not depends on what the function returns, and whether either id is NULL.
If the id column that the function returns is the same as the id value that you pass to it, and is never NULL, then the 2 queries will produce the same results.
Either way, each row of test_table1 will be joined to each row that the function produces with the argument(s) from that row. The column names produced by the function and the values in those columns are determined by the function; they do not need to have anything in common with any table. In practice, a function like f_function will usually not return an column that is always identical to any of its inputs, since that value is already available from the input.

Similar Messages

  • Joining these two queries

    I have two queries. The First one is long but very simple. All it has is long list of columns.
    First one:
    SELECT CL.CLIENT_ID, CA.CASE_ID, to_char(SYSDATE,'RRMMDD'),
    CL.MASTER_CLIENT_ID,
    CL.NAME1,
    nvl(CL.NAME2,' '),
    nvl(CL.ADDRESS1,' '),
    nvl(CL.ADDRESS2,' '),
    CL.POCO_POSTAL_CODE, nvl(CL.CITY,' '),
    nvl(CL.AUTO_SURV_CODE,0),
    CA.Col_Collector_Id
    FROM CLIENT CL, CASES CA
    WHERE CA.CL_CLIENT_ID = CL.CLIENT_ID AND
    CA.CASE_ID = :current_case_id
    Second one:
    SQL SELECT nvl(REF_NO,' '), nvl(to_char(DATE_OF_JUDGEMENT,'rrmmdd'),' ')
    FROM CASE_INSTANCES
    WHERE IN_INSTANCE_TYPE IN (1,8) AND
    CA_CASE_ID = :current_case_id AND
    PETITION_DATE = (SELECT max(PETITION_DATE)
    FROM CASE_INSTANCES
    WHERE IN_INSTANCE_TYPE IN (1,8)
    AND CA_CASE_ID = :current_case_id
    AND ROWNUM < 2 );
    The :current_case_id is passed as a parameter. The table in the second query i.e. CASE_INSTANCES is related to the first query with the CA_CASE_ID. Not all records fetched by the first query have a record in the second query. So you might have to use a LEFT JOIN or something. trying to join these two has worn me out. Please help me out someone.

    Hi,
    Simplified Solution:
    SELECT * FROM (
                        SELECT CL.CLIENT_ID, CA.CASE_ID, TO_CHAR(SYSDATE,'RRMMDD'),
                        CL.MASTER_CLIENT_ID,
                        CL.NAME1,
                        NVL(CL.NAME2,' '),
                        NVL(CL.ADDRESS1,' '),
                        NVL(CL.ADDRESS2,' '),
                        CL.POCO_POSTAL_CODE, NVL(CL.CITY,' '),
                        NVL(CL.AUTO_SURV_CODE,0),
                        CA.Col_Collector_Id
                        FROM CLIENT CL, CASES CA
                        WHERE CA.CL_CLIENT_ID = CL.CLIENT_ID ) a,
                        (SELECT NVL(REF_NO,' '), NVL(TO_CHAR(DATE_OF_JUDGEMENT,'rrmmdd'),' '),CA_CASE_ID
                             FROM CASE_INSTANCES
                             WHERE IN_INSTANCE_TYPE IN (1,8) AND
                             CA_CASE_ID = :current_case_id AND
                             PETITION_DATE = (SELECT MAX(PETITION_DATE)
                                                      FROM CASE_INSTANCES
                                                      WHERE IN_INSTANCE_TYPE IN (1,8)
                                                      AND CA_CASE_ID = :current_case_id
                                                      AND ROWNUM < 2
                        ) b
    WHERE a.case_id = b.ca_case_id(+)
    Regards
    K.Rajkumar

  • How to join the two queries

    select itm.inventory_item_id "Item#",itm.segment1,itm.description,qty.SUBINVENTORY_CODE as SHI,
    sum(qty.primary_transaction_quantity) "On Hand Qty"
    from MTL_ONHAND_QUANTITIES_DETAIL qty,
    mtl_system_items itm
    WHERE itm.inventory_item_id=qty.inventory_item_id
    and itm.ORGANIZATION_ID=qty.ORGANIZATION_ID
    and qty.SUBINVENTORY_CODE IN ('ITC-8888', 'ITC-9999')
    and trunc(qty.last_update_date) <=:P_DATE_FROM
    AND trunc(SYSDATE) >=:P_DATE_TO
    group by qty.SUBINVENTORY_CODE,itm.inventory_item_id,itm.segment1,itm.description;
    select distinct SUBSTR( kmt.tag_number, 1,6), fa.model_number from kfupm_mcr_tag kmt, fa_additions fa
    where kmt.TAG_NUMBER =fa.TAG_NUMBER ;
    and fa.model_number is not null;
    union all is not working.
    Regards
    Arifuddin

    While using the set operators, to match the number of columns in the SELECT list you can make use of NULL as:
    SELECT COL_NAME1,COL_NAME2,COL_NAME3
    FROM TAB_NAME1
    UNION
    SELECT COL_NAME1,COL_NAME2,NULL
    FROM TAB_NAME2The columns in the both SELECT lists should be same and also the datatype. The resultant of the query will be the columns of first SELECT list (column aliases)

  • Joining these these two queries (one regular and one grouped)

    Hello
    I have these two queries I would like to join, however the later is a grouped query how can I join it with the first query?
    Has to be joined on EventId. The second query is a total table scan.
    SELECT AH.EventID,
    AH.TechnicalAddress, AH.AlarmAlias, AH.AlarmPath as [OrgAlarmPath], AH.AlarmCounter as AlarmCount, AH.EventDateTime as EventTime,
    AH.[Priority], AH.AlarmMessage, AH.EventText, AH.CallListName, AH.AlarmReadDate as EndTime,
    AH.alh_EventEndedUserRemark as [EndRemark] --, SUM(seconds) here, and AlarmSessions here
    FROM AlarmHistory AH
    WHERE (AH.HeartbeatAlarm = 0 OR AH.HeartbeatAlarm IS NULL) AND
    ((AH.CallListID IS NOT NULL) OR (AH.alh_IsForStatistics = 1)) AND
    (NOT (AH.alh_t_EventSubCode is NULL or AH.AlarmReadByUserID is NULL))
    ORDER BY AH.EventID DESC
    SELECT ia.eventID, SUM(DATEDIFF(SECOND,ia.eventTime,r.eventTime)) AS seconds, COUNT(*) as AlarmSessions
    FROM alarmHistoryLog ia
    INNER JOIN alarmHistoryLog r
    ON ia.EventId = r.EventId
    AND r.EventTypeId = 2
    AND r.EventSeq = (SELECT MIN(eventSeq) FROM alarmHistoryLog WHERE eventSeq > ia.EventSeq AND EventTypeId = 2)
    WHERE ia.EventTypeId = 0
    group by ia.EventId
    order by EventId desc
    Henry

    Try the below:
    ;with ctefirst as
    SELECT AH.EventID,
    AH.TechnicalAddress, AH.AlarmAlias, AH.AlarmPath as [OrgAlarmPath], AH.AlarmCounter as AlarmCount, AH.EventDateTime as EventTime,
    AH.[Priority], AH.AlarmMessage, AH.EventText, AH.CallListName, AH.AlarmReadDate as EndTime,
    AH.alh_EventEndedUserRemark as [EndRemark] --, SUM(seconds) here, and AlarmSessions here
    FROM AlarmHistory AH
    WHERE (AH.HeartbeatAlarm = 0 OR AH.HeartbeatAlarm IS NULL) AND
    ((AH.CallListID IS NOT NULL) OR (AH.alh_IsForStatistics = 1)) AND
    (NOT (AH.alh_t_EventSubCode is NULL or AH.AlarmReadByUserID is NULL))
    ), ctesecond as
    SELECT ia.eventID, SUM(DATEDIFF(SECOND,ia.eventTime,r.eventTime)) AS seconds, COUNT(*) as AlarmSessions
    FROM alarmHistoryLog ia
    INNER JOIN alarmHistoryLog r
    ON ia.EventId = r.EventId
    AND r.EventTypeId = 2
    AND r.EventSeq = (SELECT MIN(eventSeq)
    FROM alarmHistoryLog WHERE eventSeq > ia.EventSeq AND EventTypeId = 2)
    WHERE ia.EventTypeId = 0
    group by ia.EventId
    Select A.*,B.seconds,B.AlarmSessions From ctefirst A
    Inner join ctesecond B On A.EventId = B.EventID
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped.
     [Blog]

  • Whats the difference between these two queries ? - for tuning purpose

    Whats the difference between these two queries ?
    I have huge amount of data for each table. its takeing such a long time (>5-6hrs).
    here whice one is fast / do we have any other option there apart from listed here....
    QUERY 1: 
      SELECT  --<< USING INDEX >>
          field1, field2, field3, sum( case when field4 in (1,2) then 1 when field4 in (3,4) then -1 else 0 end)
        FROM
          tab1 inner join tab2 on condition1 inner join tab3 on condition2 inner join tab4 on conditon3
        WHERE
         condition4..10 and
        GROUP BY
          field1, field2,field3
        HAVING
          sum( case when field4 in (1,2) then 1 when field4 in (3,4) then -1 else 0 end) <> 0;
    QUERY 2:
       SELECT  --<< USING INDEX >>
          field1, field2, field3, sum( decode(field4, 1, 1, 2, 1, 3, -1, 4, -1 ,0))
        FROM
          tab1, tab2, tab3, tab4
        WHERE
         condition1 and
         condition2 and
         condition3 and
         condition4..10
        GROUP BY
          field1, field2,field3
        HAVING
          sum( decode(field4, 1, 1, 2, 1, 3, -1, 4, -1 ,0)) <> 0;
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    My feeling here is that simply changing join syntax and case vs decode issues is not going to give any significant improvement in performance, and as Tubby points out, there is not a lot to go on. I think you are going to have to investigate things along the line of parallel query and index vs full table scans as well any number of performance tuning methods before you will see any significant gains. I would start with the Performance Manual as a start and then follow that up with the hard yards of query plans and stats.
    Alternatively, you could just set the gofast parameter to TRUE and everything will be all right.
    Andre

  • How do I connect two Queries?

    Hello all,
    How do I connect two Queries and add some numbers.
    Here is what I am trying to do.
    Query 1: Gets G/L Credit Amounts for Jan 2007  Feb 2007 March 2007.....Dec 2007
    Query 2: Gets G/L Debit Amounts for Jan 2007 Feb 2007 march 2007.....Dec 2007
    I need to put both these Queries in a worksheet one below the other and add the totals by each month.....so the final report looks something like this:
    I am using two structures to hold the query values.
    G/L Credit Amount        Jan 2007    Feb 2007.............Dec 2007
                                        +100         +200                   +400
    G/L Debit Amount           -50           -100                     -200
    Total                              50             100                      200
    Also, I would like to allow the users to enter Year as a variable. Any suggestions?
    Your help is greatly appreciated.

    Venkata,
    Thanks for your reply. Could you explain how I insert two query results into one worksheet? And, also how do I link the two structures ( one structure per query) so I can total the amounts by each month?
    Thank you in advance.

  • How to deal these two scenarios in SAP.

    Hi All,
    My company is Software company.My company is having many clients.
    1)Whenever we require some materials for client project he provides us required materials and our company uses them for job, there is no change in state/value of tool, we  send back the tool after usage
    2)Our vendor will place the material at our place and we will pay
    the rent for every month or quarterly.
    how to deal these two scenarios in SAP.
    Regards,
    Purush.

    hi
    create new material type for this
    >1)Whenever we require some materials for client project he provides us required materials and our >company uses them for job, there is no change in state/value of tool, we send back the tool after usage
    u can just tick for quantity update for that material type in OMS2
    then u can take it using 501 Q
    >2)Our vendor will place the material at our place and we will pay
    >the rent for every month or quarterly.
    for this u can make quantity update as above and give the rent payment from FI side using FB60
    regards
    kunal
    updating

  • How to join this two query

    Hi all,
    i have these two query .
    SELECT A.DATENUM,A.ATT_STATE,B.OT_MINUTES FROM WEB_HR.HR_ATTENDANCE A,WEB_HR.HR_OVERTIME B
              WHERE A.MONTH_ID=2 AND A.ATT_YEAR=2009 AND A.EMP_ID=1 AND A.EMP_ID=B.EMP_ID
              AND A.COMPANYCODE=1 AND A.DATENUM<=16 ORDER BY a.DATENUM;
              SELECT A.DATENUM AS VDATENUM,A.ATT_STATE AS VATT_STATE,B.OT_MINUTES AS VOT_MINUTES FROM WEB_HR.HR_ATTENDANCE A,WEB_HR.HR_OVERTIME B
              WHERE A.MONTH_ID=2 AND A.ATT_YEAR=2009 AND A.EMP_ID=1 AND A.EMP_ID=B.EMP_ID
              AND A.COMPANYCODE=1 AND A.DATENUM >16 ORDER BY a.DATENUM;
    actually from these two query each query returning 3 column each .
    so what i need is i want mearge these two in such way that it return 6 column at a time..
    can i get this??

    You can do that by just joining them. Let's assume your two queries are Q1 and Q2, both with columns c1-3, then just:
    select q1.c1, q1.c2, q1.c3, q2.c1, q2.c2, q2.c3
    from (Q1) q1
        ,(Q2) q2But this will result in a cartesian product of the two resultsets (from Q1 and Q2).
    The big question is how do you want to combine the rows that come out of Q1 with the rows that come out of Q2. For instance if DATENUM is unique in both resultsets, and you want to combine rows that have matching values on DATENUM (c1, below), then:
    select q1.c1, q1.c2, q1.c3, q2.c1, q2.c2, q2.c3
    from (Q1) q1
        ,(Q2) q2
    where q1.c1 = q2.c1Toon

  • Install NW7.0 ABAP Trial SP12 on Windows. how use/unpack these two files

    Hello,
    I tried to install the NW7.0 ABAP Trial SP12 on Windows XP. The download work properly I hope.
    I extracted the part1-file to separate folder.
    I have no idea how the second file can be extracted (part2).
    So I started the setup and it worked well, but the programm to get the hardware key isn't on in the file system "saplicense.exe".
    now my question is how do I have to use these two download files (extract, join together, how?) to get a complete installation source?
    Can anybody help me?
    Thanx in advance
    Hans

    Hi Hans,
    When you extract the part1 the others are extracted too.
    I use the program Winrar and works fine.
    What program are you using to extract?

  • How can I combine two queries ? QoQ does not work

    I have one query where I just count the total qty coming in per month, something like:
    <cfquery name="qryIn" datasource="dbname">
    select count(orderNO) as totalIN,month
    where status = "IN"
    group by month
    </cfquery>
    I then have a second query to count the total qty going out per month
    <cfquery name="qryOut" datasource="dbname">
    select count(orderNO) as totalOut,month
    where status = "OUT"
    group by month
    </cfquery>
    I then use QoQ to combine both:
    <cfquery="qryTotal" dbtype="query">
    select
    totalIN,
    totalOUT
    from qryIN,qryOUT
    where qryIN.month = qryOUT.month
    </cfquery>
    The problem I am running into is that QoQ does not allow LEFT JOIN, so that if the month is in one query but not the other, it will not pick up that record. And that is throwing off my counts.
    How can I combine  both queries, and bypass QoQ to get a qty IN and qty Out value, per month ? and, for example, if qty in exists for one month and qty Out does not exists for that month, then qty Out will be zero for that month.
    I need this data to plot a chart.
    Thanks for any help provided.

    Do it in a single query to your database.  Here is part of it.
    select month
    , sum(case when when status = "IN" then 1 else 0 end) total_in

  • How to join this two tables

    Hi
    have a two login in forms not in oracle... i have two tables first the
    Master secodn the Employees.. my prob is i have two button for this two tables to login.. any solution on how i can join this two in one button that if i connect using from master tables or from employess it will login
    FirstTAble:::
    BEGIN
    iF :username IS NULL THEN
    MESSAGE ('Please enter Username ');
    MESSAGE ('Please enter Username ');
    GO_ITEM('username');
    RAISE FORM_TRIGGER_FAILURE;
    end if;
    IF :PASSNAME1 IS NULL THEN
    MESSAGE('Please enter password.');
    MESSAGE('Please enter password.');
    GO_ITEM('PASSNAME1');
    RAISE FORM_TRIGGER_FAILURE;
    end if;
    select username,passname
    into :pass.username,:pass.passname1
    from Master
    where :pass.username=username
    and :pass.passname1=passname;
    Message('Access Granted');
    Message('Access Granted');
    go_block('maina');
    hide_view('pass1');
    exception
    when no_Data_found then
    set_alert_Property('wrong',Alert_Message_text,'Invalid Password');
    if show_alert('wrong')=alert_button1 then
              go_item('PASSNAME1');
              :passname1:=null;
              end if;
    end;
    SEcodnTAble
    BEGIN
    iF :username IS NULL THEN
    MESSAGE ('Please enter Username ');
    MESSAGE ('Please enter Username ');
    GO_ITEM('username');
    RAISE FORM_TRIGGER_FAILURE;
    end if;
    IF :PASSNAME1 IS NULL THEN
    MESSAGE('Please enter password.');
    MESSAGE('Please enter password.');
    GO_ITEM('PASSNAME1');
    RAISE FORM_TRIGGER_FAILURE;
    end if;
    select username,passname
    into :pass.username,:pass.passname1
    from Employees
    where :pass.username=username
    and :pass.passname1=passname;
    Message('Access Granted');
    Message('Access Granted');
    go_block('maina');
    hide_view('pass1');
    exception
    when no_Data_found then
    set_alert_Property('wrong',Alert_Message_text,'Invalid Password');
    if show_alert('wrong')=alert_button1 then
              go_item('PASSNAME1');
              :passname1:=null;
              end if;
    end;

    use a union on the 2 select statements.

  • Can these two queries be combined

    Is there a more eloquent way of joining the two tales to only
    get those records that have more than one record. Instead of
    writing two seperated queries, can one query achieve the
    results?

    Could this also have been solved with one query by just doing
    the following?
    <cfquery name="get_mult_posn" datasource="#dsn#">
    SELECT a.posn_id, a.pers_id, a.job_titl, frst_name,
    mid_name, last_name
    FROM posntable a, perstable b
    WHERE a.pers_id = b.pers_id
    </cfquery>

  • These two queries return same data?

    select * from voucher where (unit = 'TIA4M' or unit = 'TIAFM' or unit = 'TIAWM' or unit = 'TIATW' or unit = 'TIAPA' )
    and invoice_dt >= TO_DATE('01/01/2006', 'MM/DD/YYYY')
    select * from voucher where unit in ('TIA4M', 'TIAFM', 'TIAWM', 'TIATW', 'TIAPA')
    and invoice_dt >= TO_DATE('01/01/2007', 'MM/DD/YYYY')
    Also the first is much faster right?

    The first query is using a date of Jan 1, 2006. The second query is using a date of Jan 1, 2007.
    Assuming that is a typo, the two queries are semantically identical. Since Oracle can easily transform an IN-list to a series of OR's, though, I would doubt that there would be any performance difference between them absent the 2006/2007 change.
    Justin

  • How do I join together these two queries?

    Hi I have these queries:
    select br_no, br_managersname from BRANCH order by br_managersname;
    select sum(rent_endkms-rent_startkms) as "TOTAL KMS TRAVELLED" from RENTAL group by BR_NO having SUM(rent_endkms-rent_startkms) = (select MAX(sum(rent_endkms-rent_startkms)) from RENTAL group by BR_NO);
    They each output their own tables, but I wanna join them together so they output as one table. Unfortunately, I really suck at joining tables. Can anyone help?

    Hmm... Not enought information again... Any way, let me consider br_no as the key between the two query. In that case i came up with this.
    with query1
    as
    select br_no, br_managersname
    from BRANCH order by br_managersname
    query2
    as
    select br_no, sum(rent_endkms-rent_startkms) as total_kms_travelled
      from RENTAL
    group by BR_NO
    having SUM(rent_endkms-rent_startkms) = (select MAX(sum(rent_endkms-rent_startkms))
                                               from RENTAL
                                              group by BR_NO)
    select q1.bar_no, q1.br_managersname, q2.total_kms_travelled
      from query1 q1
      join query2 q2
        on q1.br_no = q2.br_no

  • I have these below queries. How do I join these 3 queries into a single query?

    1st query:
    SELECT TOP(1) @tmpOnlineCat = ac.AlertCatID
    FROM alert.AlertCategory ac
    WHERE ac.FkAlertID = 2
    AND ac.FkAlertTypeID = 3
    2nd query
    SELECT TOP(1) @tmpOfflineCat = ac.AlertCatID
    FROM alert.AlertCategory ac
    WHERE ac.FkAlertID = 3
    AND ac.FkAlertTypeID = 3
    3rd query
    INSERT INTO item.ItemOnlineOfflineAlertCategory
    VALUES
    @tmpPkItemID,
    @tmpOfflineCat,
    @tmpOnlineCat
    mayooran99

    I think this is all what you need!
    INSERT INTO item.ItemOnlineOfflineAlertCategory
    SELECT @tmpPkItemID,
    MAX(CASE WHEN FkAlertID = 2 THEN AlertCatID END) AS tmpOnlineCat,
    MAX(CASE WHEN FkAlertID = 3 THEN AlertCatID END) AS tmpOfflineCat
    FROM alert.AlertCategory
    WHERE FkAlertTypeID = 3
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for