Select from different tables based on value

Hi Forum,
I'm stuggling with a problem:
In a table, I have two columns, pref_type and pref_value. Column pref_type stores a number value that is linked to a preference type, whereas column pref_value stores the value of that preference.
Unfortunately, the data model is such that per preference type a different tables needs to be used, so for example, if
pref_type = 1, table to query is A, whereas if
pref_type = 2, table to query is B.
I now want to write a query that resolves the preferences, ie it should branch to the respective table based on pref_type and search for pref_value and deliver back a different column of that respective table.
My first approach was like that:
select decode (pref_value, 1, (select result from A where pref_value = ???),
2, (select result from B where pref_value = ???)
where the three ??? depict the problem I'm having, as Oracle doesn't allow me to have a harmonized subquery here.
How do I achieve this?
Thanks for any help,
J. Sieben

I believe this is what you are trying to get at:
SELECT DECODE(m.pref_type, 1, (SELECT result FROM a
                               WHERE a.pref_value = m.pref_value),
                           2, (SELECT result FROM b
                               WHERE b.pref_value = m.pref_value)
FROM my_table mAlthough, if the tables are large, that might be pretty slow. Better than an outer join, but one of those correlated queries is going to be run for each row in my_table. You could lso try something like:
SELECT m.pref_type, r.result
FROM my_table m,
     (SELECT 'A' tbl, pref_value, result
      FROM a
      UNION ALL
      SELECT 'B', pref_value, result
      FROM b) r
WHERE DECODE(m.pref_type, 1, 'A', 'B') = r.tbl and
      m.pref_value = r.pref_valueHTH
John

Similar Messages

  • How to do a SELECT from different tables into an internal table?

    How to do a SELECT from different tables into an internal table?
    I want to select data from MARA, MARC and ZPERSON and populate my ITAB_FINAL
    REPORT  zinternal_table.
    TABLES:
      mara,
      marc,
      zperson.
    TYPES:
    BEGIN OF str_table1,
      v_name LIKE zperson-zname,
      v_matnr LIKE marc-matnr,
      v_emarc LIKE marc-emarc,
      v_werks_d LIKE marc-werks_d,
      v_dstat LIKE marc-dstat,
      END OF str_table,
      i_table1 TYPE STANDARD TABLE OF str_table1.
    DATA:
    BEGIN OF str_table2,
    v_mandt LIKE mara-mandt,
    v_ernam LIKE mara-ernam,
      v_laeda LIKE mara-laeda,
    END OF str_table2,
    itab_final LIKE STANDARD TABLE OF str_table2.

    first find the link between mara , marc and zperson , if u have link to 3 tables then u can jus write a join and populate the table u want ( thats final table with all the fields).
    u defenitely have alink between mara and marc so join them and retrieve all data into one internal table.
    then for all the entries in that internal table retrieve data from zperson into another internal table.
    then loop at one internal table
    read another internal table where key equals in both the tables.
    finally assign fileds if sy-subrc = 0.
    gs_finaltable-matnr = gs_table-matnr
    etc...
    and finally append gs_finaltable to gt_finaltable.
    there u go ur final table has all the data u want.
    regards
    Edited by: BrightSide on Apr 2, 2009 3:49 PM

  • Deleting from a table based on values in a second table

    Is it possible to DELETE from (or for that matter do an UPDATE to) a table based on values in another table? I have gone through the online documentation but can't seem to find anything. I'm trying to delete rows from table A where A.field1 = B.field1 and B.field2 = 'X'. (B being the second table)

    It is done using subqueries in the where clause.
    delete from A
    where A.field1 in (select B.field1 from B where B.field2 = 'X');
    delete from A
    where exists (select 'x' from B where B.field1 = A.field1 and B.field2 = 'X');
    delete from A
    where A.rowid in (select A.ROWID from from A, B where B.field1 = A.field1 and B.field2 = 'X');
    And many other varieties. Eg. more specialised:
    delete from A
    where A.txdate < (select B.prune_date FROM B where B.field1 = A.field1 and B.field2 = 'X')
    and A.txstate in (select S.txstate from S where S.prodlass=a.prodclass and s.deletable='Y');

  • Field selection from differant tables

    hello all,
             i need to select differant fields from differant tables when i select common fields from both the tables, is it necessary that the common field need to be a primary key in both tables.
    thanks in advance
    seenu

    HI,
        No its not required that the common field be part of the primary key in both tables only thing is you need to prefix the table name if the field names are same. But if you are using a INNER JOIN then there is no need to select both fields since you know the content of both fields will be same if JOIN is ON these fileds as well.
    Regards,
    Sesh
    Message was edited by:
            Seshatalpasai Madala

  • Selection from different tables

    Hello Everyone,
    I have a situation where I have 15 fields in the selection screen.
    The selection is dependent on three or more tables.
    First I have selected from two tables but if the user enters values in the selection screen then how to make the selection.
    Tables dont have common fields between them. LIKP, LIPS, VTTK, VBUK and VEKP are the tables.
    Can you guys guide me.
    Thank you.

    Hi Vinod,
    First I have selected from two tables but if the user enters values in the selection screen then how to make the selection.
    Your query is not so clear. When are you fetching the data from two table whether before selection screen input (Initialization event) or after selection screen?
    Can you please elaborate your query and better if you post your Selection Screen screen-shot.
    Regards,
    VIjay

  • To select from database table based on date range

    hi
    i have a selection screen in which date range is being given
    say eg 23/06/07  to 23/12/08
    based on this date i want to select data from a ztable
    eg i want to select a field amount from table
    and three is a field date range on the table
    for this particular field i want to select all records for amount field  and factual field falling wiithing this date range and sum it
    eg
    based on date range as in selcetion screen
    select amount( field1)  factual ( field2) from ztable into it_ztable where date = ?....
    please give me code for it  and how to sum all values as i will get from the ztable into internal table the two values as fetched from the ztable
    please suggest asap
    regards
    arora

    hi
    i am using
    sELECT field1 field2 FROM Ztable  INto it_matu
                       where DATE GE sl_dat-low    
                        AND  DATE LE sl_dat-high.   
    i am getting data in internal table but
    say i have twelve records now i want to sum it the both the columns into and use that sum final amount to display
    let me know how to use sume in the intrranal tabl do i need to use control statement
    how to use the sum for two columns and take into a serperate variable to display
    regards
    aRora

  • Select from db table of 2 values to 2 variables

    Hi,
    is there a way, how to select 2 values from a table row to 2 variables?
    like:
    select single a b
    into ex_a
          ex_b
    from x
    where...
    Thank you,
    Olian
    Edited by: Olian Saludew on Aug 7, 2008 3:00 PM

    Like this example you can select as amny you want.
    SELECT SINGLE bukrs werks ename btrtl kostl orgeh stell plans persg INTO
        (ls_ee-bukrs, ls_ee-persa, ls_ee-ee_name, ls_ee-btrtl, ls_ee-curr_kostl, ls_ee-orgeh,
         ls_ee-job, ls_ee-plans, ls_ee-persg) FROM pa0001 WHERE
                                                          pernr EQ ls_ee-ee_no AND
                                                          begda LE sy-datum   AND
                                                          endda GE sy-datum.

  • Select from different tables depending on results

    how to do this in one select
    4 tables
    t3 and t4 are identical in structure but different data
    select id from t1
    If exists in select id from t2
    then select data from t3
    else
    select data from t4
    create table t1 (id number);
    create table t2 (id number);
    create table t3 (col1 varchar2(10), col2 varchar2(10));
    create table t4 (col1 varchar2(10), col2 varchar2(10));
    insert into t1 values(1);
    insert into t1 values(2);
    insert into t2 values(1);
    insert into t3 values('DATA1','DATA2');
    insert into t4 values('DATA3','DATA4');
    commit;
    Ive put values 1 and 2 into t1. as id=1 exists in t2, for that record I want the values from t3 but where id=2, I want the values from t4.
    Possible in one select?   Ive been playing with case statement but not getting anywhere near it

    Having multiple table with same structure looks like a design flaw. What benefit that does bring. So please explain the reason to have 2 table with same structure.
    Said that here are few more ways.
    SQL> select id
      2       , col1
      3       , col2
      4    from (
      5            select t1.id
      6                 , decode(t2.id, null, 'T4', 'T3') table_handle
      7              from t1
      8              left
      9              join t2
    10                on t1.id = t2.id
    11         ) a
    12    join (
    13            select 'T3' table_handle, col1, col2 from t3
    14            union all
    15            select 'T4' table_handle, col1, col2 from t4
    16         ) b
    17      on a.table_handle = b.table_handle;
            ID COL1       COL2
             1 DATA1      DATA2
             2 DATA3      DATA4
    SQL> select id
      2       , col1
      3       , col2
      4    from (
      5            select t1.id
      6                 , dbms_xmlgen.getxmltype('select col1, col2 from ' || decode(t2.id, null, 'T4', 'T3')) xml_data
      7              from t1
      8              left
      9              join t2
    10                on t1.id = t2.id
    11         )
    12       , xmltable
    13         (
    14            '/ROWSET/ROW' passing xml_data
    15            columns col1 varchar2(10) path 'COL1',
    16                    col2 varchar2(10) path 'COL2'
    17         );
            ID COL1       COL2
             1 DATA1      DATA2
             2 DATA3      DATA4
    SQL>

  • Best way to select from 2 tables, based on sum from detail table

    I have a "customer order line detail" table from which I want to report
    Order Number
    Customer Number
    Part Number
    Line Value { which is Unit Qty * (Unit price - discount%) }
    But only for orders which are above £1500.
    And lines which are not "Cancelled"
    I have access to an API which returns the total order value for the order.
    I am currently using this in my criteria, eg:
    select order_no, customer_no, part_no, round(unit_qty *(unit_price - unit_price *(discount/100)),2) Line_value
    from customer_detail
    where
    status != 'Cancelled'
    and
    Customer_Order_API.Get_Total_Sale_Price__(order_no)>=1500
    The API contains the following:
    SELECT SUM(ROUND((qty * price_conv_factor * unit_price), rounding_) -
    ROUND((qty * price_conv_factor * unit_price) -
    ((qty * price_conv_factor * unit_price) * ((1 - discount / 100) * (1 - order_discount / 100))), 2))
    FROM customer_detail
    WHERE order_no = order_no_
    AND state != 'Cancelled'
    AND line_item_no <= 0
    (that uses a price conversion factor that I don't use, since it's always 1)
    My query runs so slowly, because it is getting the order value for every line of the order, is it possible to improve?
    Thanks

    Thanks for the suggestion, it was close to what I needed.
    I ended up with this:
    select order_no,  name, ref_id, c_salesman_sub_division, line_value, catalog_desc
    from
    (SELECT coj.customer_no, coj.order_no, ifsapp.customer_info_api.GET_NAME(customer_no) name, coj.ref_id,
           coj.c_salesman_sub_division, ROUND((coj.buy_qty_due * coj.
           price_conv_factor) * coj.sale_unit_price, 2) - ROUND((coj.buy_qty_due *
           coj.price_conv_factor) * coj.sale_unit_price - ((coj.buy_qty_due * coj.
           price_conv_factor) * coj.sale_unit_price) * ((1 - coj.discount / 100) *
           (1 - coj.order_discount / 100)), 2) line_value, coj.catalog_desc,
    SUM( ROUND((coj.buy_qty_due * coj.
           price_conv_factor) * coj.sale_unit_price, 2) - ROUND((coj.buy_qty_due *
           coj.price_conv_factor) * coj.sale_unit_price - ((coj.buy_qty_due * coj.
           price_conv_factor) * coj.sale_unit_price) * ((1 - coj.discount / 100) *
           (1 - coj.order_discount / 100)), 2)) OVER (PARTITION BY Coj.ORDER_NO) AS SUM_ORDER
        FROM ifsapp.customer_order_join coj
        WHERE coj.order_no = coj.order_no
          AND TRUNC(coj.date_entered) = NVL(TO_DATE('25/01/2007', 'DD/MM/YYYY'),
              TRUNC(SYSDATE))
          AND coj.authorize_code = 'UKMEDM'
          AND coj.line_item_no >= 0
          AND coj.ref_id <> 'SAMP'
          AND coj.state <> 'Cancelled'
    where sum_order >=1500
        ORDER BY ref_id, c_salesman_sub_division, customer_no, order_no
    /[pre]
    But I have realised the problem with this.  Not sure if I made it clear, to myself even, but I need to include
    order lines added on a particular day (that are not cancelled)
    for orders which total >= £1500.
    If one line of an order is added for £900 but the rest of the order is £2000 then that line should be shown.
    My SQL only shows lines added for the day >= 1500.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can I do an Insert using two selects from different tables?

    Hi,
    I have three tables, Course (CID, NAME, TIME)
    Teacher (TID, NAME, DESCRIPTION) and OfferedBy(CID, TID) to match a course to a teacher.
    After I do an insert on Course, I want to be able to do an insert on OfferedBy using the CID of the course I inserted, and the TID of the teacher that's offering it.
    I tried this after doing inserts on Course and Teacher:
    INSERT INTO OfferedBy values (SELECT CID FROM Course where courseName = 'name' , SELECT TID FROM Teacher WHERE LastName = 'teacherName').
    I get an ORA 00907 error.
    What am I doing wrong? Can this actually be done?
    Thank you
    I

    Hi,
    How would you relate the TID with CID?
    I tried this after doing inserts on Course and Teacher:
    INSERT INTO OfferedBy values (SELECT CID FROM Course where courseName >= 'name' , SELECT TID FROM Teacher WHERE LastName = 'teacherName').
    I get an ORA 00907 error.You can use the query in this way:
    SQL> SELECT ( ( SELECT dummy FROM DUAL), (SELECT DUMMY FROM DUAL)) FROM DUAL;
    SELECT ( ( SELECT dummy FROM DUAL), (SELECT DUMMY FROM DUAL)) FROM DUAL
    ERROR at line 1:
    ORA-00907: missing right parenthesis
    SQL> SELECT 'AA',(SELECT dummy FROM DUAL) FROM DUAL;
    'A (
    AA X
    SQL>Regards

  • Redirecting to different pages based on value from table linked from report

    Hi,
    I wanted to navigate to different pages from a report link based on a value from the table on which the report is built. I was able to link to particular page without any problem.
    But, I wanted to link to different pages based on value in the table. Please let me know how can I do this?
    Thanks,

    kaminey wrote:
    Hi,
    I wanted to navigate to different pages from a report link based on a value from the table on which the report is built. I was able to link to particular page without any problem.
    But, I wanted to link to different pages based on value in the table. Please let me know how can I do this?APEX version?
    Is this a standard or interactive report?
    How does the value from the table determine the target page used in the link? Is it a page number? Or the result of some computation or process?
    When you have a problem you'll get a faster, more effective response by including as much relevant information as possible upfront. This should include:
    <li>Full APEX version
    <li>Full DB/version/edition/host OS
    <li>Web server architecture (EPG, OHS or APEX listener/host OS)
    <li>Browser(s) and version(s) used
    <li>Theme
    <li>Template(s)
    <li>Region/item type(s) (making particular distinction as to whether a "report" is a standard report, an interactive report, or in fact an "updateable report" (i.e. a tabular form)
    With APEX we're also fortunate to have a great resource in apex.oracle.com where we can reproduce and share problems. Reproducing things there is the best way to troubleshoot most issues, especially those relating to layout and visual formatting. If you expect a detailed answer then it's appropriate for you to take on a significant part of the effort by getting as far as possible with an example of the problem on apex.oracle.com before asking for assistance with specific issues, which we can then see at first hand.

  • How to populate a table based on a row selection from another table.

    Hi, i just started to use ADF BC and Faces. Could some one help me or point me a solution on the following scenario .
    By using a search component , a table is being displayed as a search result. If i select any row in the resulted table , i need to populate an another table at the bottom of the same page from another view. These two tables are related by primary key . May i know how to populate a table based on a row selection from another table. Thanks
    ganesh

    I understand your requirement and the tutorial doesn't talk about Association between the views so that you can create a Master-Detail or in DB parlance, a Parent-Child relationship.
    I will assume that we are dealing with two entities here: Department and Employees where a particular Department has many Employees and hence a Parent-Child relationship.
    Firstly, you need to create an Association between the two Entities - Department and Employees. You can do that by right clicking on the model's entity and then associating the two entities with the appropriate key say, DepartmentId.
    Once you have done that, you need to link the two entities in the View section with this Association that you created. Then go to AppModule and make sure that in the Available View Objects: 'EmployeesView' appears under 'DepartmentView' as "EmployeesView via <link you created>". Shuttle the 'DepartmentView' to the right, Data Model and then shuttle
    "EmployeesView via <link you created>" to the right, Data Model under 'DepartmentView'.
    This will then be reflected in your Data Controls. After that, you simply would have to drag this View into your page as a Master-Detail form...and then when you run this page, any row selected in the Master table, would display the data in the Detail table.
    Also, refer to this link: [Master-Detail|http://baigsorcl.blogspot.com/2010/03/creating-master-detail-form-in-adf.html]
    Hope this helps.

  • Report using Data from different tables

    Hello,
    I am trying to convert a Cobol batch program to Oracle 6i tabular report.
    The data is fetched from many different tables and there are lots of processing(i.e, based on the value of a column from one table need additional processing from different tables) required to generate the desired columns in the final report.
    I would like to know what is the best strategy to follow in Oracle Reports 6i. I heard that CREATE GLOBAL TEMPORARY TABLE is an option. ( or REF CURSOR ?) I do not know much about its usage. Can somebody guide me about this or any other better way to achieve the result.
    Thank you in advance
    Priya

    Hello,
    There are many, many options available to you, each of which has advantages and disadvantages. This is why it is difficult to answer "what is best?" without alot more details about your specific circumstances.
    In general, you're going to be writing PL/SQL to do any conditional logic that cannot be expressed as pure SQL. It can executed in the database, or it can executed within Reports itself. And most reports developers do some of both.
    As a general rule, you want to send only the data you need from the database to the report. This means you want to do as much filtering and aggregating of the data as is readily possible within the database. If this cannot be expressed as plain SQL queries, then you'll want to create a stored procedures to help do this work.
    Generally, the PL/SQL you create for executing within the report should be focused on control of the formatting, such as controlling whether a field is visible, or controlling display attributes for conditional formatting.
    But these are not hard and fast rules. In some cases, it is difficult to get all the stored procedures you might like installed into the database. Perhaps the dba is reluctant to let you install that many stored procedures. Perhaps there are restrictions when and how often updates can be made to stored procedures in a production database, which makes it difficult to incrementally adjust your reports based on user feedback. Or perhaps there are restrictions for how long queries are allowed to run.
    So, Reports offers lots of options and features to let you do data manipulation operations from within the report data model.
    In any case, Oracle does offer temporary table capabilities. You can populate a temp table by running stored procedures that do queries, calculations and aggregations. And you can define and initiate a dynamic query statement within the database and pass a handle to this query off to the report to execute (ref cursor).
    From the reports side, you can have as many queries as you want in the data model, arranged in any hierarchy via links. You can parameterize and change the queries dynamically using bind variables and lexicals. And you can add calculations, aggregations, and filters.
    Again, most people do data manipulation both in the database and in Reports, using the database for what it excels at, and Reports for what it excels at.
    Hope this helps.
    Regards,
    The Oracle Reports Team --skw                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to display multiple data from different table in one table? please help

    Hi
    I got sun java studio creator 2(the separate installation not the one in the net beans)....
    My question is about displaying data that have been taken from the database.... I know how to display data in a table(just click on the table "bind data" )... but my question is that:
    when i want to use a sql statement that taken the data from different table...
    how can i display that data in the table(that will be shown in the web) ??? when i click bind data on the table i can only select one table i can't select more than one....
    Note:
    1) i'm using the rowset for displaying the data in the table, since the sql statement is depending on a condition(i.e. select a from b where c= ? )...
    2) i mean by different table is that( i.e. select a from table1,table2 )..
    thanks in advance...

    Hi,
    937440 wrote:
    Hi every one, this is my first post in this portal. Welcome to the forum!
    Be sure to read the forum FAQ {message:id=9360002}
    I want display the details of emp table.. for that I am using this SQL statement.
    select * from emp where mgr=nvl(:mgr,mgr);
    when I give the input as 7698 it is displaying the corresponding records... and also when I won't give any input then it is displaying all the records except the mgr with null values.
    1)I want to display all the records when I won't give any input including nulls
    2)I want to display all the records who's mgr is null
    Is there any way to incorporate to include all these in a single query..It's a little unclear what you're asking.
    The following query always includes rows where mgr is NULL, and when the bind variable :mgr is NULL, it displays all rows:
    SELECT  *
    FROM     emp
    WHERE     LNNVL (mgr != :mgr)
    ;That is, when :mgr = 7698, it displays 6 rows, and when :mgr is NULL it displays 14 rows (assuming you're using the Oracle-supplied scott.emp table).
    The following query includes rows where mgr is NULL only when the bind variable :mgr is NULL, in which case it displays all rows:
    SELECT     *
    FROM     emp
    WHERE     :mgr     = mgr
    OR       :mgr       IS NULL
    ;When :mgr = 7698, this displays 5 rows, and when :mgr is NULL it displays 14 rows.
    The following query includes rows where mgr is NULL only when the bind variab;e :mgr is NULL, in which case it displays only the rows where mgr is NULL. That is, it treats NULL as a value:
    SELECT     *
    FROM     emp
    WHERE     DECODE ( mgr
                , :mgr, 'OK'
                )     = 'OK'
    ;When :mgr = 7698, this displays 5 rows, and when :mgr is NULL, it displays 1 row.

  • Select from two tables and insert into a third

    I'm trying to do a select from two tables and do an insert into a third table from the two resulting columns.
    I have the following....
    DECLARE
    tempsid number;
    temphostid number;
    BEGIN
    select "DBSID_ID","ID" into tempsid,temphostid from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" ("SIDLOOKUP_ID", "SERVERLOOKUP_ID")
    values(tempsid, temphostsid);
    END;
    run;
    I get the error ....
    ORA-06550: line 11, column 18:
    PL/SQL: ORA-00984: column not allowed here
    ORA-06550: line 10, column 1:
    PL/SQL: SQL Statement ignored
    1. DECLARE
    2. tempsid number;
    3. temphostid number;

    okay ... I tried a different way ...
    DECLARE
    a number;
    b number;
    BEGIN
    select "DBSID_ID","ID" into a,b from "DBSIDS","SERVERS"
    where "HOST_SID" like '%'||"DBSID_NAME"||'%'
    and "HOST_NAME" not like 'vio%'
    and exists (select "DBSID_NAME" from DBSIDS)
    order by "DBSID_NAME";
    insert into "DBSID_LOOKUP" (SIDLOOKUP_ID, SERVERLOOKUP_ID) values (a, b);
    END;
    and now it whines about ...
    ORA-01422: exact fetch returns more than requested number of rows

Maybe you are looking for