CASE and JOIN Query Help

I have two Tables
Table A
ID                             VALUE           
1                         Delhi                
2                      Mumbai                
3                      Bangalore
Table B
TYPE                        TYPE_A_ID                         TYPE_B_ID             
A                      1                                 NA                   
A                      1                                 NA                
B                      NA                                2           
A                      3                                 NA                  
B                      NA                                    1                   
A                      1                                 NA            I want to get the value from Table A, depending on the Type in Table B
i.e., when the Type is A, the value in Type_A_ID should be looked up in Table A
and when the Type is B, the value in Type_B_ID should be looked up in Table A.
The result how i need is as follows:
TYPE                        TYPE_A_ID                         TYPE_B_ID                 Value      
A                         1                                 NA                     Delhi
A                      1                                 NA                     Delhi
B                      NA                                2                      Mumbai
A                      3                                 NA                     Bangalore       
B                      NA                            1                      Delhi       
A                      1                                 NA                     Delhi

Here you go...
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>
SQL&gt; DROP TABLE A;
Table dropped.
SQL&gt; CREATE TABLE A ( ID INTEGER, VALUE VARCHAR2(20));
Table created.
SQL&gt; INSERT INTO A VALUES(1,'Delhi');
1 row created.
SQL&gt; INSERT INTO A VALUES(2,'Mumbai');
1 row created.
SQL&gt; INSERT INTO A VALUES(3,'Bangalore');
1 row created.
SQL&gt; DROP TABLE B;
Table dropped.
SQL&gt; CREATE TABLE B(TYPE CHAR(1), TYPE_A_ID CHAR(2), TYPE_B_ID CHAR(2));
Table created.
SQL&gt; INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL&gt; INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL&gt; INSERT INTO B VALUES ('B','NA','2');
1 row created.
SQL&gt; INSERT INTO B VALUES ('A','3','NA');
1 row created.
SQL&gt; INSERT INTO B VALUES ('B','NA','1');
1 row created.
SQL&gt; INSERT INTO B VALUES ('A','1','NA');
1 row created.
SQL&gt; COMMIT;
Commit complete.
SQL&gt;
SQL&gt; SELECT TYPE, TYPE_A_ID, TYPE_B_ID, VALUE
2 FROM A, (SELECT TYPE, TYPE_A_ID, TYPE_B_ID, DECODE(TYPE_A_ID,'NA',TYPE_B_ID,TYPE_A_ID) ID FROM B) B
3 WHERE A.ID = B.ID
4 /
T TY TY VALUE
A 1 NA Delhi
A 1 NA Delhi
B NA 1 Delhi
A 1 NA Delhi
B NA 2 Mumbai
A 3 NA Bangalore
6 rows selected.
</code></pre>
Karthick
http://www.karthickarp.blogspot.com/

Similar Messages

  • Using Case and Joins in update statement

    Hi all,
    I need to update one column in my table...but need to use case and joins...I wrote the query and it is not working
    I am getting an error msg saying...the SQL command not ended properly...
    I am not that good at SQL...Please help...
    update t1 a
    set a.name2=
    (case
    when b.msg2 in ('bingo') then '1'
    when b.msg2 in ('andrew') then '2'
    when b.msg2 in ('sam') then '3'
    else '4'
    end )
    from t1 a left outer join t2 b
    on a.name1 = b.msg1 ;
    Waiting for help on this...!
    Thanks in Advance... :)

    Another approach is to update an inline view defining the join:
    update
    ( select a.name2, b.msg2
      from   t1 a
      join   t2 b on b.msg1 = a.name1 ) q
    set q.name2 =
        case
          when q.msg2 = 'bingo' then '1'
          when q.msg2 = 'andrew' then '2'
          when q.msg2 = 'sam' then '3'
          else '4'
        end;which could also be rewritten as
    update
    ( select a.name2
           , case q.msg2
                when 'bingo'  then '1'
                when 'andrew' then '2'
                when 'sam'    then '3'
                else '4'
             end as new_name
      from   t1 a
      join   t2 b on b.msg1 = a.name1 ) q
    set name2 = new_name;The restriction is that the lookup (in this case, t2.msg1) has to be declared unique, via either a primary or unique key or unique index.
    (You don't strictly need to give the view an alias, but I used 'q' in case you tried 'a' or 'b' and wondered why they weren't recognised outside the view.)

  • Join query help

    hi
    i am encountering error like the values not getting populated in internal table though values are in dbtable...so if u can help me out in the join query it will be of gr8 help
    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'.
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.
    thnx

    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'.
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.
    SELECT a1~guid a1~posting_date a1~process_type
           b1~sales_org b1~division b1~dis_channel
           INTO CORRESPONDING FIELDS OF TABLE it_ordel
           FROM ( ( crmd_orderadm_h AS a1 INNER JOIN crmd_link AS c1 ON a1~guid  = c1~guid_hi )
                    INNER JOIN crmd_orgman AS b1 ON c1~guid_hi = b1~guid )
           WHERE c1~objtype_hi = '05'
           AND   c1~objtype_set = '21'    ".              delete that period its wrong
        AND   a1~process_type IN so_prst
           AND   a1~posting_date IN so_podt
           AND   b1~division     IN so_div.

  • Case and Decode query

    Hi,
    I am running below statement.
    create table test_abc
    (cnt number,
    outcome varchar2(20));
    insert into test_abc values(1,'EXISTINGDOMFUELCUST');
    insert into test_abc values(1,'Answer Phone');
    insert into test_abc values(1,'Answer Phone');
    insert into test_abc values(1,'Answer Phone');
    insert into test_abc values(1,'Answer Phone');
    insert into test_abc values(1,'Answer Phone');
    commit;
    Now I used case and decode
    select count(*),ot from (
    select (case when outcome ='EXISTINGDOMFUELCUST' then 'Existing Domestic Fuel Customer'
    when outcome='Answer Phone' then 'Answer Phone'
    when outcome='Answer Phone' then 'Answer Machine' end) ot
    from test_abc)
    group by ot;
    select count(*),decode(outcome,'EXISTINGDOMFUELCUST','Existing Domestic Fuel Customer','Answer Phone',
    'Answer Phone','Answer Phone','Answer Machine')
    from test_abc
    group by decode(outcome,'EXISTINGDOMFUELCUST','Existing Domestic Fuel Customer','Answer Phone',
    'Answer Phone','Answer Phone','Answer Machine')
    and getting same output
    cnt ot
    5 Answer Phone
    1 Existing Domestic Fuel Customer
    but I want output should be
    cnt ot
    5 Answer Phone
    5 Answer Machine
    1 Existing Domestic Fuel Customer
    please suggest

    Indra Budiantho wrote:
    /* Formatted on 8/28/2012 3:10:28 PM (QP5 v5.139.911.3011) */
    SELECT CASE
    WHEN outcome = 'EXISTINGDOMFUELCUST'
    THEN
    'Existing Domestic Fuel Customer'
    WHEN outcome = 'Answer Phone'
    THEN
    'Answer Phone'
    END
    outcome,
    COUNT (*)
    FROM test_abc
    GROUP BY outcome
    union
    SELECT CASE
    WHEN outcome = 'EXISTINGDOMFUELCUST'
    THEN
    'Existing Domestic Fuel Customer'
    WHEN outcome = 'Answer Phone'
    THEN
    'Answer Machine'
    END
    outcome,
    COUNT (*)
    FROM test_abc
    where outcome = 'Answer Phone'
    GROUP BY outcomeo/p
    Answer Machine     5
    Answer Phone     5
    Existing Domestic Fuel Customer     1This can be simplified..
    Also, UNION will unnecessarily do a distinct operation.
    SELECT CASE
                WHEN outcome = 'EXISTINGDOMFUELCUST'
                THEN
                   'Existing Domestic Fuel Customer'
                WHEN outcome = 'Answer Phone'
                THEN
                   'Answer Phone'
             END
                outcome,
             COUNT (*)
        FROM test_abc
    GROUP BY outcome
    union all
    SELECT 'Answer Machine'
                outcome,
             COUNT (*)
        FROM test_abc
        where outcome = 'Answer Phone'
    GROUP BY outcome

  • Left Join query help

    select * from ort
    bid mid
    18083 7
    select * from st
    tid bid mid act
    318 18083 5 20091
    318 18083 6 20091
    321 18083 7 NULL
    318 18083 16 23970
    my out put should be
    318 18083 6 20091
    (basic idea is
    In order to do this I wrote the following query. But I am getting the following error ora-01799. How do i fix this?
    select ort.bid,st.tid from ort
    left join st
    on ort.BiD = st.bid
    and st.mid in
    (select max(MID)
    from St
    where BID = ort.BID and TID is not null and MID <= ort.MID
    and ACT is not null
    )

    May be this will clear up what I am trying to acheive a little better. I truly appreciate all your help. I have enclosed column headings and data items within double quotes and data is enclosd in double-quotes and separated by comma.
    SQL> desc ort
    "Name" "Null?" "Type"
    "BID" "NUMBER"
    "MID" "NUMBER"
    SQL> desc st
    "Name" "Null?" "Type"
    "TID" "NUMBER"
    "BID" "NUMBER"
    "MID" "NUMBER"
    "ACT" "NUMBER"
    "LTP" "NUMBER(10)"
    SQL> select * from ort
    2 ;
    "BID" "MID"
    "18083", "7"
    "18083", "6"
    "18083", "16"
    "18083", "277"
    "18083", "117"
    SQL> select * from st;
    "TID" "BID" "MID" "ACT" "LTP"
    "NULL", "18083", "117", "NULL", "246"
    "NULL", "18083", "277", "NULL", "246"
    "246", "18083", "272", "54998", "246"
    "318", "18083", "6", "20091" "NULL"
    "321", "18083", "7", "NULL", "NULL"
    "318", "18083", "16", "23970", "NULL"
    6 rows selected.
    SQL> SELECT ort.bid, st.tid, st.mid, st.act
    2 FROM ort
    3 LEFT OUTER JOIN
    4 st
    5 ON ort.bid = st.bid
    6 AND st.mid IN (SELECT mid
    7 FROM myortview);
    "BID" "TID" "MID" "ACT"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    SQL> -- expected result is
    bid tpid ort.mid st. mid
    "18083", "246", "277", "272"
    "18083", "246", "117", "116"
    "18083", "318", "16", "16"
    "18083", "318", "6", "6"
    "18083", "318", "7", "6"

  • SQL Join query help

    Hello,
    I have two select statements as
    Query 1 : Select col1,col2,col3,col4,value_a from table_1
    Query 2: Select col1,col2,col3,col4,value_b from table_2
    I want to join these two select statement to get below result.
    col1 col2 col3 col4 value_a value_b
    Scenario 1: Both query fecth the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    1 TK TL TM 100
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    1 TK TL TM 200
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TK TL TM 100 200
    Scenario 2: Only query 1 fetches the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    1 TN TO TP 300
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TN TO TP 300 0
    Scenario 3: Only query 2 fetches the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    1 TN TO TP 300
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TN TO TP 0 300
    How should I join these?

    Because you want a FULL OUTER JOIN .
    select
       t1.*, t2.*
    from
       table_1 t1
       full outer join table_2 t2
    on
             t2.col1 = t1.col1
       and   t2.col2 = t1.col2
       and   t2.col3 = t1.col3
       and   t2.col4 = t1.col4
    )Please read the FAQ and learn how to post questions, so you can format your code, etc...
    http://wiki.oracle.com/page/Oracle+Discussion+Forums+FAQ

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

  • Query to get a listing of all folders and joins in EUL

    If anybody has a query that provides a listing of all folders and joins between those folders in a Discoverer EUL, can you please share it.
    Any help would be greatly appreciated.

    Hi
    As Rod commented you won't get an accurate listing going through XREFS. You need to look in the statistics table, EUL5_QPP_STATS where you will find a history of all worksheets that have been executed. Unfortunately the item columns in EUL5_QPP_STATS are encoded so you will need some special SQL to uncode them.
    First of all you will need to have installed the EUL extensions which can be found in the script called EUL5.SQL (located in the Discoverer\Util folder where Admin is installed) when logged in as the owner of the EUL. Theh try running this script, altering the data switch to a suitable date:
    SELECT
    QS.QS_DOC_OWNER    USER_NAME,
    QS.QS_DOC_NAME     WORKBOOK,
    QS.QS_DOC_DETAILS  WORKSHEET,
    TRUNC(QS.QS_CREATED_DATE) EXECUTION_DATE,
    *(LENGTH(TO_CHAR(EUL5_GET_ITEM_NAME(QS.QS_ID)))+1)/9 ITEMS,*
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),1,  6)) ITEM1,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),10, 6)) ITEM2,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),19, 6)) ITEM3,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),28, 6)) ITEM4,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),37, 6)) ITEM5,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),46, 6)) ITEM6,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),55, 6)) ITEM7,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),64, 6)) ITEM8,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),73, 6)) ITEM9,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),82, 6)) ITEM10,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),91, 6)) ITEM11,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),100,6)) ITEM12,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),109,6)) ITEM13,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),118,6)) ITEM14,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),127,6)) ITEM15,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),136,6)) ITEM16,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),145,6)) ITEM17,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),154,6)) ITEM18,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),163,6)) ITEM19,
    EUL5_GET_ITEM(SUBSTR(EUL5_GET_ITEM_NAME(QS.QS_ID),172,6)) ITEM20
    FROM
    EUL5_QPP_STATS QS
    WHERE
    *(LENGTH(TO_CHAR(EUL5_GET_ITEM_NAME(QS.QS_ID)))+1)/9 < 21*
    AND QS.QS_CREATED_DATE > '01-JAN-2009'
    Best wishes
    Michael

  • Different Between In and Join Function of Query

    Hi Team,
    I have confuse for the below query getting different count.
    Version DB :-
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE     11.2.0.1.0     Production
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    Query:-1
    Getting Count :-3917
    SELECT COUNT (*)
      FROM stg_ser_level_inv_db a, map_stg_gsm_serv b
    WHERE a.account_number_v IN (SELECT account_number_v
                                    FROM map_transaction_number MAP
                                   WHERE MAP.trans_type_v IN ('F', '4'))
       AND a.trans_num_v
                        IN (SELECT trans_num_v
                              FROM map_transaction_number MAP
                             WHERE MAP.trans_type_v IN ('F', '4'))
       AND a.trans_type_v
                         IN (SELECT trans_type_v
                               FROM map_transaction_number MAP
                              WHERE MAP.trans_type_v IN ('F', '4'))
       AND a.acct_no = b.stg_account_number
       AND a.serv_account_number_v= b.stg_serv_link_code
       AND NOT EXISTS (
              SELECT 1
                FROM cb_sub_ar_ap ar
               WHERE ar.account_link_code_n = b.ab_serv_acc_link_code
                 AND ar.bill_cleared_flg_v = 'N'
                 AND ar.trans_num_v IN (SELECT target_trans_num_v
                                          FROM map_transaction_number MAP
                                         WHERE MAP.trans_type_v IN ('F', '4')))--3917why when u IN condition and join condition count is different. please let me know why?
    Thanks for advance ...
    Second :-2 Join Condition
    Total Count :-789948
    select COUNT(*)
        FROM STG_SER_LEVEL_INV_DB A , MAP_STG_GSM_SERV B,MAP_TRANSACTION_NUMBER ARAP_CUR
    WHERE  A.ACCOUNT_NUMBER_V = ARAP_CUR.ACCOUNT_NUMBER_V
    AND A.TRANS_NUM_V  = ARAP_CUR.TRANS_NUM_V
    AND A.TRANS_TYPE_V = ARAP_CUR.TRANS_TYPE_V
    AND A.ACCT_NO = B.STG_ACCOUNT_NUMBER
    and a.SERV_ACCOUNT_NUMBER_V  = B.STG_SERV_LINK_CODE
    and ARAP_CUR.TRANS_TYPE_V in ('F','4')
    and not exists (select 1 from CB_SUB_AR_AP ar
          where ar.account_link_code_n = B.AB_SERV_ACC_LINK_CODE
          and AR.BILL_CLEARED_FLG_V = 'N'
          and ar.trans_num_v = ARAP_CUR.TARGET_TRANS_NUM_V);---789948

    Hi,
    Whenever you have a problem, please post a complete test script that people can run to re-create the problem and test their ideas. Include a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data. In this case, data that produced no more than 10 rows of output for each query should be plenty.
    Simplify the problem as much as possible. For example, it looks like both your queries are joining tables a and b the same way. Why not pretend that you have only 1 table, ab, that is the same as the result set of joining a and b? Post CREATE TABLE and INSERT statements for the relevant columns of ab.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    There are several differences between those two queries.
    For one thing, Query 1 is doing a 2-way join between a and b, and then filtering that result set by comparing it to another table (let's call it map). So if a contains 5 rows and b contains 2 rows, the result set will contain at most 5 * 2 = 10 rows. Perhaps only 8 of those 10 rows will have matching rows in map. Note that the number of rows in map, or how many rows in map match rows in a or b doesn't matter. Query 2, on the other hand, is doing a 3-way join of a, b and map, so if map has 100 rows, the result set could have as many as
    (5 * 2) * 100 = 1000 rows. We know that it won't have that many rows, because only 8 out the rows from the a-b join have matching rows in map, but the result set of the 3-way join could still have as many as
    (8) * 100 = 800 rows.
    Since you didn't post test versions of your tables, I'll use tables from the scott schema to illustrate. Scott.dept has 4 rows, only 3 of which match rows in scott.emp, so
    SELECT  d.*
    FROM     scott.dept  d     -- tables a and b in your query play this role
    WHERE     d.deptno  IN (
                      SELECT  e.deptno
                   FROM     scott.emp  e     -- map plays this role in your query
    ;produces 3 rows of output. Exactly how many rows are in emp (that number happens to be 14) and how many of those rows match rows in dept (that happens to be 14, also) doesn't matter; all that matters in the query above is that 3 of the rows in dept have matches. However, the fact that 14 of the rows in emp have matches is important in the query bleow:
    SELECT     d.*
    FROM     scott.dept  d
    JOIN     scott.emp   e  ON  d.deptno  = e.deptno
    ;which produces 14 rows of output.
    Another differece is that Query 1 says that there are 3 conditions that relate table a to map; a given row in a will be included in the result set if any row in map meets condition 1, any row in map meets condition 2, and any row in map meets condition 3. It doesn';t matter if you have to look at 2 or 3 rows in map to meet all those conditions. Query 2 says that a row from a will be included only if there is a single row in map that meets all 3 conditions.

  • Self Joining and Inline Query. A tricky report.

    I am stuck with a very tricky situation.Please help.This is PROD issue.
    I have written a SQL code which has 1 inline queries,and displays the right results
    with the right report output
    Dont get confused.Just go thru this.
    select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
    from position_master_input_event pie,
    (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
    from instrument ins, instrument_xref insx
    where ins.id_inst = insx.id_inst
    and   insx.flg_active = 'Y'
    and   ins.flg_active  = 'Y'
    group by insx.id_inst_xref_type,insx.id_inst_xref
    )PN
    where     id_entity = 'AGL'
    and       pie.id_inst_code *= PN.id_inst_xref
    and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
    group by  pie.id_inst_code,PN.Active,
    Table :Instrument_xref
    id_inst      id_inst_xref_type    id_inst_xref  flg_active
    0372285      SE                   B0DV8Y9       Y
    0372285      IS                   GB00B03MLX29  Y
    Table :Instrument
    id_inst      id_inst_xref_type    id_inst_xref  flg_active  flg_primary_listing
    0372285      SE                   B0DV8Y9       Y           N 
    OUTPUT:
    id_inst_xref                      Active
    B0DV8Y9                           1
    PERFECT.Works fine
    2) Now comes the tricky part.:
        0372285 also has GB00B03MLX29 which has flg_active to Y and which also maps to 0372285.
        Am I right?
        New reportOutput
        id_inst_xref                      Active   PRIMARY ISIN
        B0DV8Y9                           1        1
        So,now I want a SELF JOIN this way built into the code:
        (hardcoded values work)
        (i)
        select  a.id_inst_xref
        from instrument_xref a,
             instrument_xref b
        where b.id_inst_xref ='B0DV8Y9'
        and   b.id_inst = a.id_inst
        and   b.id_inst_xref_type in ('SE','IS')
        and   a.id_inst_xref =  'GB00B03MLX29'
        (ii)
         select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
         And now LINKING ALL :
        select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
        from position_master_input_event pie,
        (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
         from instrument ins, instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_active  = 'Y'
         group by insx.id_inst_xref_type,insx.id_inst_xref
        )PN,
        (select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
          and     insx.id_inst_xref = ( 
                                           select  DISTINCT  a.id_inst_xref
                                            from    instrument_xref a,
                                            instrument_xref  b
                                      where b.id_inst_xref = 'B0DV8Y9'
                                          and     b.id_inst = a.id_inst
                                          and     b.id_inst_xref_type in ('SE','IS')
                                       and    a.id_inst_xref =  'GB00B03MLX29'
        where     id_entity = 'AGL'
        and       pie.id_inst_code *= PN.id_inst_xref
        and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
        group by  pie.id_inst_code,PN.Active,
        THE Self join works fine as long as it is hardcoded.
        But assume there can br multiple such situations as the above,and I dont want to
        hardcode the values,how can I build the NEW REPORT by SELF JOINING.
        Please can someome help.This is a tricky one.
        Is there a better way to this

    Isn't this the same question as:
    Passing values dynamically Froman 'INLINE Query' to a 'SUB QUERY'
    and
    Another query regarding Inline Query and Self Join and pass Column Values

  • My iphone 5s isn't turning on and its not charging. i have my legit charger that came with my phone and after 6 months it stopped working, i even have a charging case and that wont charge i. I tried cleaning it but still nothing! some please help

    A few days after i've updated to iOS 8.1.1 my iphone 5s died and isn't turning on and its not charging. i have my legit charger that came with my phone and after 6 months it stopped working, i even have a charging case and that wont charge it. I google searched the problem and tried cleaning the charging port but still nothing! some please help

    Please make a Genius Appointment and take it in for service.
    If your iPod Touch, iPhone, or iPad is Broken
    Apple does not fix iDevices. Instead, they exchange yours for a refurbished or new replacement depending upon the age of your device and refurbished inventories. On rare occasions when there are no longer refurbished units for your older model, they may replace it with the next newer model.
    ATTN: Beginning July 2013 Apple Stores are now equipped to do screen repairs/replacements in-house on iPhone 5 and 5C. In some cases while you wait. According to Apple this is the beginning of equipping Apple Stores with the resources needed to do most repairs for iPhones, iPads, and iPod Touches that would not require major replacements. Later in the year the services may be extended as Apple Stores become equipped and staffed with the proper repair expertise. So, if you need a screen repaired or a broken screen replaced or have your stuck Home button fixed, call your local Apple Store to see if they are now doing these in-house.
    You may take your device to an Apple retailer for help or you may call Customer Service and arrange to send your device to Apple:
    Apple Store Customer Service at 1-800-676-2775 or visit online Help for more information.
    To contact product and tech support: Contacting Apple for support and service - this includes international calling numbers.
    You will find respective repair costs in the appropriate link:
    iPod Service Support and Costs
    iPhone Service Support and Costs
    iPad Service Support and Costs
    There are third-party firms that do repairs on iDevices, and there are places where you can order parts to DIY if you feel up to the task:
    1. iResq or Google for others.
    2. Buy and replace screen yourself: iFixit

  • Joins query between itab and database table..

    Hi all,
    Is it posible to use joins query between internle table and data base table...

    Hi Mehboob,
    No thats impossible to join the internal table and the database table.
    Alternatively what you need to do is you need to execute a Queryin Database Table and use the For All Entries in itab.
    Eg:  Select * from marc into table it_marc
             for all entries in it_matnr
               where matnr = it_matnr-matnr.
    Thanks,
    Chidanand

  • Case with select into and sub query

    hi im trying to use case and select with sebqueries, but my beginer like understanding of syntax fails me. can someone point out what im doing wrong in the case select below. im using select into, as i ultimatly need to load a ref cursor for use with crystal reports.
    thanks
    james
    ps if anyone is london based, and would like to spend a day or two teaching me how to be a bit better at PL/SQL (can aford to pay a little bit) please get in touch!!
    SELECT
    Case (select kind_code from event where                    
    event.event_id = event.container_event_id)     
    when 1094006
    then          promo_name     
    end
    into      result
    FROM promo,     promo_plan ,     event_promotion
    WHERE      promo.promo_id = promo_plan.promo_id
    AND     promo_plan.promo_plan_id = event_promotion.promo_plan_id
    AND     event_promotion.detail_id = '33532282'
    when blah then 'blah';

    Hello
    AH i see what you are driveing at, yes i am just using case slect to determin which >routine to run, as the name is stored in a diferent location depending on the event kind >code. are are you saying i need multiple selects within the case statment? one for each >type of kind code?Well it depends really. If the select
    select kind_code from event where
    event.event_id = event.container_event_idIs going to return more than one row for any given run, you're going to need to take a bit of a different approach. Is it the case that this query will return more than one row which would mean that you want value X and value Y for each row?
    Using the test data and everything from before:
    SQL> CREATE OR REPLACE PROCEDURE p_GetStuff(ac_Result   OUT sys_refcursor)
      2  IS
      3
      4  BEGIN
      5     /*
      6             This uses a cartesian product i.e. repeat every row in
      7             dt_test_data against every row in dt_test_event
      8     */
      9     OPEN Ac_Result FOR
    10     SELECT
    11             CASE dt_test_event.kind_code
    12             WHEN 1 THEN
    13                     dt_test_data.object_name
    14             WHEN 2 THEN
    15                     dt_test_data.object_type
    16             END
    17     FROM
    18             dt_test_data,
    19             dt_test_event;
    20
    21  END;
    22  /
    Procedure created.
    SQL> var x refcursor
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    TABLE
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    TABLE
    TABLE
    TABLE
    TABLE
    INDEX
    INDEX
    INDEX
    INDEX
    INDEX
    20 rows selected.Or an alternative to that would be, if you have a fixed number of event ids and they relate to a fixed number of attributes you could use something like:
    CREATE OR REPLACE PROCEDURE p_GetStuff3(ac_Result     OUT sys_refcursor)
    IS
    BEGIN
              The SUBSTR
              is just there to make sure the data fit on screen, my SQL*Plus
              is a bit weird!
         OPEN Ac_Result FOR
         SELECT
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,1,dt_test_data.object_name,NULL)),1,30) attribute_1,
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,2,dt_test_data.object_type,NULL)),1,30) attribute_2
         FROM
              dt_test_data,
              dt_test_event
         GROUP BY
              object_name;
    END;
    SQL> delete from dt_test_event where kind_code=2;
    1 row deleted.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC                            TABLE
    ABC4                           TABLE
    AD1                            TABLE
    AD2                            TABLE
    ADHOC_CONTACT_LOG              TABLE
    AK_CD_CLAIM_VALIDATION_SOURCE  INDEX
    AK_CD_CLAIM_VALIDATION_TYPE    INDEX
    AK_CLAIM_ACTION_ROWSOURCE      INDEX
    APPROVAL_LIST_MEM_IE           INDEX
    APPROVE_GRP_HIST_IE            INDEX
    10 rows selected.Message was edited by:
    david_tyler
    Oops, copy + pasted the wrong comments for the 2nd proc.

  • Who to query and join nested elements

    I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes.  The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes.  My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless.  Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
    <RasDataSet>
       <PerstrenList>
            <Perstren>
               <TPERS>A</TPERS>
               <DEPLY>B</DEPLY>
               <STRUC>5</STRUC>
               <RemarksList>
                   <REMARK>
                        <LABEL>ABC</LABEL>
                        <GENTEXT>Hello world</GENTEXT>
                   </REMARK>
                   <REMARK>
                        <LABEL>XYZ</LABEL>
                        <GENTEXT>Oracle XML</GENTEXT>
                   </REMARK>
               <RemarksList>
            </Perstren>
            <Perstren>
           <TPERS>C</TPERS>
           <DEPLY>D</DEPLY>
           <STRUC>4</STRUC>
           <RemarksList>
               <REMARK>
                    <LABEL>EFG</LABEL>
                    <GENTEXT>Database</GENTEXT>
               </REMARK>
           <RemarksList>
            </Perstren>
            <Perstren>
           <TPERS>E</TPERS>
           <DEPLY>F</DEPLY>
           <STRUC>3</STRUC>
            </Perstren>       
       <PerstrenList>
    </RasDataSet>
    desired Results
    TPERS  DEPLY   LABEL  GENTEXT
    A       B       ABC   Hello World
    A       B       XYZ   Oracle XML
    C       D       EFG   Database
    select uic,
            extractvalue(Column_value,'/Perstren/TPERS') as TPERS,
            extractvalue(Column_value,'/Perstren/DEPLY') as DEPLY,
            extractvalue(Column_value,'/Perstren/SECUR') as SECUR,
            extractvalue(Column_value,'/Perstren/STRUC') as STRUC,
            extractvalue(Column_value,'/Perstren/TIME') as TIME,
            extractvalue(Column_value,'/Perstren/AUTH') as AUTH,
            extractvalue(Column_value,'/Perstren/ASGD') as ASGD,
    from test_ref doc,
        table(XMLSequence(extract(doc.XML_DOC,'/RasDataSet/PerstrenList/Perstren'))) per
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Sorry my Pre tag was in the wrong place Text reads:
    I have a table that contains a XMLTYPE Field. How do I query and join nested elements. For example I have a schema that has a PerstrenList element that holds one or more Perstren nodes. The Perstren node will contain a RemarksList node that can contain one or more Remarks nodes. My goal is to query all of the Remarks and join them with the information in it's parent node. Without the parent node information the remark is meaningless. Following is a example document and desire result set. I know how to query the Perstren or the Remarks I just can not figure out how to marry the two. The query should only return the remarks joined with the parent information.
    Sorry my Pre tag was in the wrong place

Maybe you are looking for

  • EDI: Receiver port in control record is invalid

    Yesterday, we got refreshed out quality system with the production SAP system. I am trying to process IDoc # QXXXXXXX  in quality but I am getting the following error message: EDI: Receiver port in control record is invalid. To create this IDoc, I co

  • MBA wireless shows not connected

    Hi, my MacBook Air (early 2014) connects to the Internet and then for several minutes scrolls looking for a wifi to connect to. It then tells me that there is no Internet connection ans puts an exclamation mark over the grayed bars of the wifi symbol

  • Creating A New Oracle Database And Sql Developer

    Hi, I'm a newbie to Oracle and and a not so newbie to Sql Server and Visual Studio. I am trying to learn Oracle on my local machine. I want to create a new Oracle Database and start learning from there. I have downloaded sql developer, the data model

  • Patch installer not overwriting the existing one

    Patch installer not overwriting the existing one Hi, for one my LabVIEW application, I have created two installers Including all the required additional installers (Installer) With no additional installer (patch installer) So that, for further versio

  • Need input on creating archive pool in IXos. What is the best practise ..

    In my company we are using ixos as archiving content server. I will like to know what is the standard /general configuration which is used while creating Archive POOL in ixos. What is the Best practice DO we create one archive for each type of docume