Need help with self join query

Hello,
I have table A with the following data
oid parent_oid
10 4
4 2
2 2
12 6
6 6
parent_oid is the parent of oid. I'd like a query that shows the final parent of the oid. The result should show the following
oid final parent
10 2
4 2
2 2
12 6
6 6
I'm using Oracle 10g. I'm familiar with self joins, but that alone will not do the job. Thanks!

Hi,
arizona9952 wrote:
... I'm familiar with self joins, but that alone will not do the job.You're absolutely right!
A 2-way self join would work for rows have no parent, or rows that are directly connected to their final ancestor (such as oid=4), but not for anything farther away.
A 3-way self-join would work for one more level away from the final row, but no more. That would be enough for the small set of sample data that you posted, but it would not work if you added a new row with parent_id=10.
An N-way self-join would work for up to N+1 levels, but no more.
You need something that can go any number of levels, such as CONNECT BY:
SELECT     CONNECT_BY_ROOT oid     AS oid
,     parent_oid          AS final_parent
FROM     a
WHERE     CONNECT_BY_ISLEAF     = 1
CONNECT BY     oid     = PRIOR parent_oid
     AND     oid     != parent_oid
;Edited by: Frank Kulash on Feb 22, 2010 7:09 PM
Upon sober reflection, I think that a Top-Down query, like the one below, would be more efficient than a Bottom-Up query, like the one above:
SELECT     oid
,     CONNECT_BY_ROOT     parent_oid     AS final_parent
FROM     a
START WITH     parent_oid     = oid
CONNECT BY     parent_oid     = PRIOR oid
     AND     oid          != PRIOR oid
;

Similar Messages

  • Need help with Update Join Query

    Hello, I am trying to update PID of #child table with PID of #parent table if "lastname & firstname are matches in both table" but my update query is giving some error. Please help and correct the update query. I am also trying to remove any
    blank space from starting and ending.
    drop table #parent,#child
    create table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #parent values ('100','Josheph','Sumali')
    insert into #parent values ('400','Karen','Hunsa')
    insert into #parent values ('600','Mursan  ','  Terry')
    create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #child values ('2','Josheph ','Sumali   ')
    insert into #child values ('5','Karen','Kunsi')
    insert into #child values ('6','Mursan ','Terry ')
    Update #child
    set PID = p.PID
    from #child C Join
    #parent p ON c.LTRIM(RTRIM(lastname) = p.LTRIM(RTRIM(lastname)
    AND c.LTRIM(RTRIM(firstname) = p.LTRIM(RTRIM(firstname)
    /* Requested Output */
    PID        lastname      firstname
    100        Josheph       Sumali
    600        Mursan        Terry

    create table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #parent values ('100','Josheph','Sumali')
    insert into #parent values ('400','Karen','Hunsa')
    insert into #parent values ('600','Mursan ',' Terry')
    create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
    insert into #child values ('2','Josheph ','Sumali ')
    insert into #child values ('5','Karen','Kunsi')
    insert into #child values ('6','Mursan ','Terry ')
    Merge #child as t
    Using #parent as p ON (LTRIM(RTRIM(t.lastname)) = LTRIM(RTRIM(p.lastname))
    AND LTRIM(RTRIM(t.firstname)) = LTRIM(RTRIM(p.firstname)) )
    When Matched Then
    Update
    set PID = p.PID;
    update #child
    Set lastname=LTRIM(RTRIM(lastname)), firstname= LTRIM(RTRIM(firstname));
    update #parent
    Set lastname=LTRIM(RTRIM(lastname)), firstname = LTRIM(RTRIM(firstname));
    select * from #child
    select * from #parent
    drop table #parent,#child

  • Need help with a JOIN query

    Hi,
    I am looking for the following result:
    PROVIDER_ID     SPECIALTY     BUCKET     CODE     RATING     FEE
         1     FP                 EM     100     9     20
         1     FP                 SP     300     15     0
         1     INFUS                 EM     100     3     20
         1     INFUS                 EM     200     6     15The base tables are provided below in the with clause. What I am trying to do is, where "code" matches show the fee from t1 else show 0.
    I tried a few variotions but just can't seem to get it right.
    with t1 as
    select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 200 as code, 15 as fee, 30 as default_multiplier from dual
    , t2 as
    select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
    select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
    select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
    select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
    SELECT   t1.provider_id
           , t2.specialty
           , t2.bucket
           , t2.code
           , t2.rating
           , t1.fee
    FROM     t1, t2
    ORDER BY 1, 2, 3Any help will be appreciated.
    Thanks.

    Could I possibly add one more twist to this.
    The current result:
    PROVIDER_ID SPECI BU       CODE     RATING        FEE
              1 FP    EM        100          9         20
              1 FP    SP        300         15          0
              1 INFUS EM        100          3         20
              1 INFUS EM        200          6         75
              2 FP    EM        100          9         40
              2 FP    SP        300         15          0
              2 INFUS EM        100          3         40
              2 INFUS EM        200          6          0
              3 FP    EM        100          9          0
              3 FP    SP        300         15          0
              3 INFUS EM        100          3          0
              3 INFUS EM        200          6         60The current code:
    with t1 as
    select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 200 as code, 75 as fee, 10 as default_multiplier from dual union all
    select 1 as provider_id, 500 as code, 75 as fee, 10 as default_multiplier from dual union all
    select 2 as provider_id, 100 as code, 40 as fee, 20 as default_multiplier from dual union all
    select 3 as provider_id, 200 as code, 60 as fee, 30 as default_multiplier from dual
    , t2 as
    select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
    select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
    select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
    select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
    , t3 as
    SELECT   t1.provider_id
           , t2.specialty
           , t2.bucket
           , t2.code
           , t2.rating
           , CASE t1.code
                WHEN t2.code
                   THEN t1.fee
                ELSE 0
             END AS fee
           , RANK () OVER (PARTITION BY t1.provider_id, t2.specialty, t2.bucket, t2.code ORDER BY CASE t1.code
                 WHEN t2.code
                    THEN t1.fee
                 ELSE 0
              END DESC) AS the_rank
        FROM t1
           , t2
    SELECT DISTINCT provider_id
                  , specialty
                  , bucket
                  , code
                  , rating
                  , fee
               FROM t3
              WHERE the_rank = 1
           ORDER BY 1
                  , 2
                  , 3
                  , 4I added the code 500 to t1. Howevere, I don't want this code to show up in the result becuase it is does not exist in t2.
    I also added code 200 to t1, to see if that shows properly.
    I had to do the rank, becuase I need the proper count of rows.
    In reality the row counts are:
    t1: 20 Million
    t2: 10 Thousand.
    So, I would like to avoid doing DISTINCT and ANALYTIC functions on this large set, so any better way of achiving the same result, with a better statement.
    Thanks.

  • Help with self join query

    Hello people,
    I have the table MENUS on 9i with the folowing fields:
    MENU_ID, PARENT_ID, MENUNAME,...
    and some sample data:
    0,999999,ROOT
    7,0,NETWORK
    6,0,SERVICES
    100,0,CUSTOMERS
    74,7,MONITORING
    88889081,7,CONFIG
    88890006,7,TEST
    88890049,7 TEST II
    88889163,6,MAIL
    61,6,SMS
    So PARENT_ID shows under which menu the submenu exists.
    I need to create the below report:
    ROOT
    *NETWORK
    **CONFIG
    **TEST
    **TEST II
    *SERVICES
    **MAIL
    **SMS
    *CUSTOMERS
    Stars or any other way to identify the level depth will be very handful.
    Thank you in advance.

    Hi,
    Try to relate with this example on emp table.
    select empno,ename,level,sys_connect_by_path(ename,'/') as path
    from emp
    start with mgr is null
    connect by prior empno=mgrOutput
    EMPNO ENAME LEVEL PATH
    7839  KING      1       /KING
    7566  JONES    2      /KING/JONES
    7788  SCOTT   3      /KING/JONES/SCOTT
    7876  ADAMS   4      /KING/JONES/SCOTT/ADAMS
    7902  FORD     3      /KING/JONES/FORD
    7369  SMITH    4     /KING/JONES/FORD/SMITH
    7698  BLAKE    2     /KING/BLAKE
    7499  ALLEN    3     /KING/BLAKE/ALLEN
    7521  WARD    3    /KING/BLAKE/WARD
    7654  MARTIN  3    /KING/BLAKE/MARTIN Hope it helps
    CKLP

  • I need help with a SELECT query - help!

    Hello, I need help with a select statement.
    I have a table with 2 fields as shown below
    Name | Type
    John | 1
    John | 2
    John | 3
    Paul | 1
    Paul | 2
    Paul | 3
    Mark | 1
    Mark | 2
    I need a query that returns everything where the name has type 1 or 2 but not type 3. So in the example above the qery should bring back all the "Mark" records.
    Thanks,
    Ian

    Or, if the types are sequential from 1 upwards you could simply do:-
    SQL> create table t as
      2  select 'John' as name, 1 as type from dual union
      3  select 'John',2 from dual union
      4  select 'John',3 from dual union
      5  select 'Paul',1 from dual union
      6  select 'Paul',2 from dual union
      7  select 'Paul',3 from dual union
      8  select 'Paul',4 from dual union
      9  select 'Mark',1 from dual union
    10  select 'Mark',2 from dual;
    Table created.
    SQL> select name
      2  from t
      3  group by name
      4  having count(*) <= 2;
    NAME
    Mark
    SQL>Or another alternative if they aren't sequential:
    SQL> ed
    Wrote file afiedt.buf
      1  select name from (
      2    select name, max(type) t
      3    from t
      4    group by name
      5    )
      6* where t < 3
    SQL> /
    NAME
    Mark
    SQL>Message was edited by:
    blushadow

  • Need help with writing a query with dynamic FROM clause

    Hi Folks,
    I need help with an query that should generate the "FROM" clause dynamically.
    My main query is as follows
    select DT_SKEY, count(*)
    from *???*
    where DT_SKEY between 20110601 and 20110719
    group by DT_SKEY
    having count(*) = 0
    order by 1; The "from" clause of the above query should be generated as below
    select 'Schema_Name'||'.'||TABLE_NAME
    from dba_tables
    where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
    Any pointers will be appreciated.
    Thanks
    rogers42

    Hi,
    rogers42 wrote:
    Hi Folks,
    I need help with an query that should generate the "FROM" clause dynamically.
    My main query is as follows
    select DT_SKEY, count(*)
    from *???*
    where DT_SKEY between 20110601 and 20110719
    group by DT_SKEY
    having count(*) = 0
    order by 1; The "from" clause of the above query should be generated as below
    select 'Schema_Name'||'.'||TABLE_NAME
    from dba_tables
    where OWNER = 'Schema_Name'
    Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
    Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
    Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
    Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
    Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
    -- Preliminary Query:
    COLUMN     my_table_name_col     NEW_VALUE my_table_name
    SELECT     table_name     AS my_table_name_col
    FROM     all_tables
    WHERE     owner          = 'SCOTT'
    AND     table_name     LIKE 'E%';
    -- Main Query:
    SELECT     COUNT (*)     AS cnt
    FROM     scott.&my_table_name
    ;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
    Edited by: Frank Kulash on Aug 11, 2011 2:30 PM

  • Help with self join

    I need help to optimize this query - it's taking too long and the report times out - it jins to itself:
    /* Formatted on 2005/03/01 14:12 (Formatter Plus v4.8.5) */
    sELECT-- /*+ FIRST_ROWS */
    --SELECT /*+ ROWID*/
    aud.inv_id change_value_1, aud.inv_id change_value_2,
    audit_inventory_reports_pkg.get_audit_inventory_desc
    (aud.inv_id) item_modified,
    x.trust_xfr_code original_value, aud.trust_xfr_code new_value,
    aud.inf_app_user record_modified_by,
    INITCAP (aud.inf_client_info) client_package_information,
    aud.inf_module application, NULL record_created_on,
    aud.inf_date_change record_modified_on,
    DECODE (aud.inf_action_type,
    'INSERT', 'TRUST TRANSFER ADDED',
    'DELETE', 'TRUST TRANSFER REMOVED',
    'TRUST TRANSFER MODIFIED'
    ) modification_type
    FROM inf_p_inventory aud, inf_p_inventory x
    WHERE aud.inf_action_type = 'UPDATE'
    AND x.inv_id = aud.inv_id
    AND x.trust_xfr_code != aud.trust_xfr_code
    AND x.inf_action_type IN ('INSERT', 'UPDATE')
    AND x.inf_id IN (SELECT MAX (y.inf_id)
    FROM inf_p_inventory y
    WHERE y.inv_id = aud.inv_id AND y.inf_id < aud.inf_id)
    AND aud.inf_date_change BETWEEN TO_DATE ('20050201', 'YYYYMMDD')
    AND TO_DATE ('20050228', 'YYYYMMDD') + .99999
    and rownum<10
    order by aud.inf_date_change
    Plan:
    Operation     Object Name     Rows     Bytes     Cost     Object Node     In/Out     PStart     PStop
    SELECT STATEMENT Optimizer Mode=CHOOSE          1           10158
    SORT ORDER BY          1      80      10151                     
    COUNT STOPKEY                                        
    FILTER                                        
    HASH JOIN          1      80      10138                     
    TABLE ACCESS BY INDEX ROWID     PAUDIT.INF_P_INVENTORY     24 K     1 M     4248                     
    INDEX RANGE SCAN PAUDIT.INF_DTX_P_INV_IDX     74 K          200      
    TABLE ACCESS FULL PAUDIT.INF_P_INVENTORY     1 M     19 M     5424      
    SORT AGGREGATE          1      10                          TABLE ACCESS BY INDEX ROWID PAUDIT.INF_P_INVENTORY1 10 7           
    INDEX RANGE SCAN PAUDIT.INF_PK_P_INV_IDX     4      3                     
    Brand new statistics, good indexes:
    CREATE TABLE INF_P_INVENTORY
    INF_ID NUMBER(12) NOT NULL,
    INF_ACTION_TYPE VARCHAR2(12 BYTE) NOT NULL,
    INF_DATE_CHANGE DATE NOT NULL,
    INF_ATLAS_PROC VARCHAR2(1 BYTE),
    INF_ATTEMPTS NUMBER(12),
    INF_CLIENT_INFO VARCHAR2(64 BYTE),
    INF_DATE_XFRD DATE,
    INF_DBL_DATE_XFRD DATE,
    INF_APP_USER VARCHAR2(64 BYTE),
    INF_DB_USER VARCHAR2(30 BYTE),
    INF_DW_PROCESSED DATE,
    INF_EXCEPTION_ID NUMBER(12),
    INF_LOGON_TIME DATE,
    INF_MACHINE VARCHAR2(64 BYTE),
    INF_MODULE VARCHAR2(48 BYTE),
    INF_OSUSER VARCHAR2(30 BYTE),
    INF_PROGRAM VARCHAR2(48 BYTE),
    INF_TERMINAL VARCHAR2(30 BYTE),
    INV_ID NUMBER(12),
    SMR_GLOBAL_NAME VARCHAR2(60 BYTE),
    SMR_TIME_STAMP DATE,
    PROJECT_ID VARCHAR2(4 BYTE),
    UNIT_NUM VARCHAR2(6 BYTE),
    SEASON_CODE VARCHAR2(3 BYTE),
    SEASON_SEQ_NUM VARCHAR2(2 BYTE),
    INV_STATUS_CODE VARCHAR2(3 BYTE),
    ELEMENT VARCHAR2(3 BYTE),
    ELEMENT_DESC VARCHAR2(35 BYTE),
    OEB_CODE VARCHAR2(1 BYTE),
    HOLD_CONTRACT VARCHAR2(1 BYTE),
    CLUB_RELATED VARCHAR2(1 BYTE),
    CLUB_USAGE_CREDITS NUMBER(12),
    SELL_TYPE_CODE VARCHAR2(3 BYTE),
    USAGE_TYPE_CODE VARCHAR2(3 BYTE),
    MBR_CONTR_ID NUMBER(12),
    HOLD_DATE DATE,
    HOLD_EXP DATE,
    EXP_DATE DATE,
    HELD_BY_USER VARCHAR2(30 BYTE),
    HOLD_REASON VARCHAR2(80 BYTE),
    NUM_YRS_BOUGHT NUMBER(2),
    ORIG_EXP_DATE DATE,
    NUM_YRS_USED NUMBER(2),
    FUTURE_EXP_DATE DATE,
    APN_NUM VARCHAR2(20 BYTE),
    RESALE_EXP_DATE DATE,
    BOOK VARCHAR2(240 BYTE),
    PAGE_NUM VARCHAR2(240 BYTE),
    BOOK_PAGE_DATE DATE,
    OEB_ACTIVE_DEACTIVE NUMBER(1),
    GROUP_ID NUMBER(12),
    STATE_INTERVAL_NUM VARCHAR2(20 BYTE),
    STATE_UNIT_WK_NUM VARCHAR2(20 BYTE),
    DATE_MODIFIED DATE,
    MODIFIED_BY VARCHAR2(30 BYTE),
    LAST_ASSESS_DATE DATE,
    TRANSFER_PROJECT VARCHAR2(4 BYTE),
    BATCH_ID NUMBER(12),
    COURTHOUSE_CODE VARCHAR2(3 BYTE),
    TRUST_XFR_CODE VARCHAR2(6 BYTE),
    TRUST_XFR_CODE_REASON VARCHAR2(240 BYTE),
    PTS_TRANSFER VARCHAR2(1 BYTE),
    PTS_TRANSFER_DATE DATE,
    TRANSFER_POINTS NUMBER,
    TRANSFER_DATE DATE,
    TRANSFER_BY VARCHAR2(30 BYTE),
    TRANSFER_CODE VARCHAR2(1 BYTE),
    LAST_ASSESSED_TO VARCHAR2(3 BYTE)
    TABLESPACE xxx

    how big is your inf_p_inventory table, i mean how many records does it has as compare to the other table?

  • 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

  • Need help with LikeFilter for querying the keyset instead of value

    Hi,
    I'm looking for help with the LikeFilter.
    I need to query the cache to get all entries with key starting with a particular string.
    I could see samples using LikeFilter for querying the values in the cache but not the keyset.
    Can someone help?
    E.g:
    Cache Entries:
    abc123 - value1
    abc234 - value2
    bcd123 - value3
    I want to get all entries with key starting with 'abc'.
    thanks,
    rama.

    NJ, thanks for the quick reply.
    I tried something similar (as below) but this code gives me 'java.lang.NoClassDefFoundError: com/tangosol/util/ValueExtractor'.
    KeyExtractor extractor = new KeyExtractor("getKey");
    Filter filter = new LikeFilter(extractor, id+":%",'-',false);
    -rama.
    Edited by: 911950 on Feb 2, 2012 1:18 PM

  • Need help with the following query

    I have the following data
    INVOICE_ID PAID_AMT PYMNT_GROSS_AMT DISCOUNT
    10151 1375 1375 55
    10151DC -44.81 -44.81 0
    20017 25 25 7
    Ok the data I want to grab the discount field is paid_amt = pymnt_gross_amt and discount <> 0. If however there is another invoice_id out there (same invoice ID except with a DC appended to it like 10151DC) then you want to select the differece between the discount field without the DC and the Invoice ID with the DC the paid_amt field.
    So the results would be.
    Invoice_ID Discount
    10151 10.19
    20017 7
    Thanks for all your help!

    Why scan same table twice when it can be achived using single scan :
    Hope this helps :
    with inv_data as
    (select '10151' invoice_id,
    1375 paid_amt,
              1375 pymnt_gross_amt,
              55 discount from dual
    union all
    select '10151DC' invoice_id,
    -44.81 paid_amt,
              -44.81 pymnt_gross_amt,
              0 discount from dual
    union all
    select '20017' invoice_id,
    25 paid_amt,
              25 pymnt_gross_amt,
              7 discount from dual)
    select replace(invoice_id,'DC') invoice_id,
    sum(case when invoice_id like '%DC' then pymnt_gross_amt
         else discount end) discount
    from inv_data
    group by replace(invoice_id,'DC')
    INVOICE DISCOUNT
    10151 10.19
    20017 7
    2 rows selected.

  • Need help with outer joins

    I have the following table structure,
    Table - 1_
    ID | Information
    1 | abcadskasasa
    2 | asdasdasdasd
    3 | saeqdfdvsfcsc
    Table - 2_
    ID | PID
    1 | 12
    1 | 13
    2 | 14
    1 | 15
    1 | 16
    2 | 12
    Table - 3_
    ID | PARID
    1 | 12
    2 | 14
    1 | 15
    Now I want to select for each ID in table 1, the count of number of PID from table 2 and count of number of PARID from table 3.
    Desired output:_
    ID | COUNT_PID | COUNT_PARID
    1 | 4 | 2
    2 | 2 | 1
    3 | 0 | 0
    Could anyone please help me out with this. I am trying to make use of outer joins, but as I work mostly on the front end so, not able to come up with a proper solution for the above.
    Thanks in advance,
    Tejas

    Hi, Tejas,
    You might have been doing the outer join correctly.
    There's another problem here: joining table_1 to two other tables with which it has a one-to-many relationship.
    If you were joining table_1 to just one other table, you could say:
    SELECT       t1.id
    ,       COUNT (t2.pid)     AS count_pid
    FROM              table_1     t1
    LEFT OUTER JOIN  table_2     t2     ON     t1.id     = t2.id
    GROUP BY  t1.id
    ORDER BY  t1.id;You could have done the exact same thing with table_3 instead of table_2.
    But you can't do the same thing with both table_2 and table_3 at the same time: that would be like cross-joining table_2 and table_3. Instead of showing id=1 having count_pid=4 and count_parid=2, you would get cout_pid=8 and count_parid=8 (since 8 = 4 * 2).
    You can do a separate GROUP BY on (at least) one of the tables.
    This gets the right results. In the main query, there is only one one-to-many relationship.
    WITH  t3_summary     AS
         SELECT    id
         ,       COUNT (parid)     AS count_parid
         FROM       table_3
         GROUP BY  id
    SELECT       t1.id
    ,       COUNT (t2.pid)     AS count_pid
    ,       MAX (t3.count_parid)     AS count_parid
    FROM              table_1     t1
    LEFT OUTER JOIN  table_2     t2     ON     t1.id     = t2.id
    LEFT OUTER JOIN      t3_summary     t3     ON     t1.id     = t3.id
    GROUP BY  t1.id
    ORDER BY  t1.id;

  • Need help with inner join and distinct rows

    Hey Guys,
    i have
    1) BaseEnv Table 
    2) Link Table
    3) BaseData Table
    Link table has three columns Id,BaseEnvId,BaseDataId 
    the BaseEnvID is unique in the table where as BaseDataId can be repeated i.e multile rows of BaseEnv Table can point to same BaseData  table row
    Now i want to do  BaseEnvTable inner join Link Table inner join BaseData Table and select 5 columsn ; Name,SyncName,Version,PPO,DOM  from the BaseData table.. the problem is that after i do the inner join I get duplciate records..
    i want to eliminate the duplicate records , can any one help me here

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. Now we have to guess and type, guess and type, etc. because of your bad manners. 
    CREATE TABLE Base_Env
    (base_env_id CHAR(10) NOT NULL PRIMARY KEY,
    Think about the name Base_Data; do you have lots of tables without data? Silly, unh? 
    CREATE TABLE Base_Data
    (base_data_id CHAR(10) NOT NULL PRIMARY KEY,
    Your Links table is wrong in concept and implementation. The term “link” refers to a pointer chain structure used in network databases and makes no sense in RDBMS. There is no generic, magic, universal “id” in RDBMS! People that do this are called “id-iots”
    in SQL slang. 
    We can model a particular relationship in a table by referencing the keys in other tables. But we need to know if the relationship is 1:1, 1:m, or n:m. This is the membership of the relationship. Your narrative implies this: 
    CREATE TABLE Links
    (base_env_id CHAR(10) NOT NULL UNIQUE
       REFERENCES Base_Env (base_env_id),
     base_data_id CHAR(10) NOT NULL
       REFERENCES Base_Data (base_data_id));
    >> The base_env_id is unique in the table where as base_data_id can be repeated I.e multiple rows of Base_Env Table can point [sic] to same Base_Data table row. <<
    Again, RDBMS has no pointers! We have referenced an referencing tables. This is a fundamental concept. 
    That narrative you posted has no ON clauses! And the narrative is also wrong. There is no generic “name”, etc. What tables were used in your non-query? Replace the ?? in this skeleton: 
    SELECT ??.something_name, ??.sync_name, ??.something_version, 
           ??.ppo, ??.dom
    FROM Base_Env AS E, Links AS L, Base_Data AS D
    WHERE ?????????;
    >> I want to eliminate the duplicate records [sic], can any one help me here?<<
    Where is the sample data? Where is the results? Please read a book on RDBMS so you can post correct SQL and try again. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Need help with conditional join....

    Table 1 - Student
    ID# Name
    1 # A
    2 # B
    3 # C
    4 # D
    Table2 - Marks
    ID Marks Display
    1 # 10 # Y
    1 # 20 # Y
    1 # 14 # N
    2 # 12 # N
    2 # 13 # N
    3 # 12 # Y
    Result...Need query to do this?..
    Want to join above two tables and display marks as X when there is no ID in table marks or there is ID but all marked with display as 'N'...if there is one or more
    marked with Y then display with marks..
    I am using oracle 11i.
    ID NAme      Marks
    1 # A     #     10
    1 # A     #     20
    2 # B # X
    3 # C # 12
    4 # D # X

    Or, using ANSI join syntax:
    with Table1 as (
                    select 1 id,'A' name from dual union all
                    select 2,'B' from dual union all
                    select 3,'C' from dual union all
                    select 4,'D' from dual
         Table2 as (
                    select 1 id,10 marks,'Y' display from dual union all
                    select 1,20,'Y' from dual union all
                    select 1,14,'N' from dual union all
                    select 2,12,'N' from dual union all
                    select 2,13,'N' from dual union all
                    select 3,12,'Y' from dual
    -- end of on-the-fly data sample
    select  t1.id,
            name,
            nvl(to_char(marks),'X') marks
      from      Table1 t1
            left join
                Table2 t2
              on (
                      t2.id = t1.id
                  and
                      display = 'Y'
      order by id
            ID NAME                                                    MARKS
             1 A                                                       10
             1 A                                                       20
             2 B                                                       X
             3 C                                                       12
             4 D                                                       X
    SQL> SY.

  • Need help with outer join filter.

    Need a little help filtering a resultset and I cant seem to find a proper way to do this.
    /*table*/
    create table invoice( farinvc_invh_code varchar2(100),
                                  farinvc_item varchar2(100),
                                  farinvc_po varchar2(100)
       create table po(
            supplier_number varchar2(60),
            supplier_invoice_no varchar2(60),
            po_number varchar2(60),
            run_date varchar2(60),
            PO_LINE_NUMBER varchar2(60) );
    /*data*/
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO_ITEM) VALUES ('I0554164', '1', 'P0142245');
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO_ITEM) VALUES ('I0554164', '3', 'P0142245');
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554165', '1', 'P0142246');
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554165', '2', 'P0142246');
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529132260', 'P0142245', '21-NOV-12', '1');
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529137831', 'P0142245', '21-NOV-12', '3');
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529137831', 'P0142245', '21-NOV-12', '2');
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100122', '145678', 'P0142246', '22-NOV-12', '1');
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100122', '145679', 'P0142246', '22-NOV-12', '2');query im executing.
    SELECT  farinvc_invh_code,
                    supplier_number,
                    supplier_invoice_no,
                    farinvc_item,
                    farinvc_po ,
                    po_number,
                    run_date,
                    PO_LINE_NUMBER
            FROM INVOICE, PO
            WHERE PO_NUMBER = FARINVC_PO(+)
            AND FARINVC_ITEM(+) = PO_LINE_NUMBER
            result
    "FARINVC_INVH_CODE"           "SUPPLIER_NUMBER"             "SUPPLIER_INVOICE_NO"         "FARINVC_ITEM"                "FARINVC_PO"                  "PO_NUMBER"                   "RUN_DATE"                    "PO_LINE_NUMBER"             
    "I0554165"                    "914100122"                   "145678"                      "1"                           "P0142246"                    "P0142246"                    "22-NOV-12"                   "1"                          
    "I0554165"                    "914100122"                   "145679"                      "2"                           "P0142246"                    "P0142246"                    "22-NOV-12"                   "2"                          
    "I0554164"                    "914100121"                   "529132260"                   "1"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "1"                          
    "I0554164"                    "914100121"                   "529137831"                   "3"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "3"                          
    ""                            "914100121"                   "529137831"                   ""                            ""                            "P0142245"                    "21-NOV-12"                   "2"                           this is a much larger table and I took an excerpt in order to keep things clear and understanding. I would like to filter this result set to only show the lines that have have the po numbers are the same and line are the same but there is an extra item. in other words like such.
    "FARINVC_INVH_CODE"           "SUPPLIER_NUMBER"             "SUPPLIER_INVOICE_NO"         "FARINVC_ITEM"                "FARINVC_PO"                  "PO_NUMBER"                   "RUN_DATE"                    "PO_LINE_NUMBER"             
    "I0554164"                    "914100121"                   "529132260"                   "1"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "1"                          
    "I0554164"                    "914100121"                   "529137831"                   "3"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "3"                          
    ""                            "914100121"                   "529137831"                   ""                            ""                            "P0142245"                    "21-NOV-12"                   "2"                          

    fair enough frank lets add some extra data to the tables.
    for example.
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554167', '1', 'P0142447')
    INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554167', '2', 'P0142447')
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV1', 'P0142247', '25-NOV-12', '1')
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV2', 'P0142247', '25-NOV-12', '2')
    INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV3', 'P0142247', '25-NOV-12', '3')if we run the query above we get
    "FARINVC_INVH_CODE"           "SUPPLIER_NUMBER"             "SUPPLIER_INVOICE_NO"         "FARINVC_ITEM"                "FARINVC_PO"                  "PO_NUMBER"                   "RUN_DATE"                    "PO_LINE_NUMBER"             
    "I0554164"                    "914100121"                   "529132260"                   "1"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "1"                          
    "I0554164"                    "914100121"                   "529137831"                   "3"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "3"                          
    ""                            "914100121"                   "529137831"                   ""                            ""                            "P0142245"                    "21-NOV-12"                   "2"                          
    ""                            "914100123"                   "INV2"                        ""                            ""                            "P0142247"                    "25-NOV-12"                   "2"                          
    ""                            "914100123"                   "INV1"                        ""                            ""                            "P0142247"                    "25-NOV-12"                   "1"                          
    ""                            "914100123"                   "INV3"                        ""                            ""                            "P0142247"                    "25-NOV-12"                   "3"                           where really what im trying to target is pos and lines that have a match in both tables and there is additional items from the po table that do not have have a match from the invoice table. Furthermore i would only like to see the items that are repeating invoice numbers, in other words my result here should still only be, because "SUPPLIER_INVOICE_NO" is repeating and it does find a match for the po in the invoice table but yet there is an item with the same invoice and po in the po table that does not have a match in the invoice table.
    "FARINVC_INVH_CODE"           "SUPPLIER_NUMBER"             "SUPPLIER_INVOICE_NO"         "FARINVC_ITEM"                "FARINVC_PO"                  "PO_NUMBER"                   "RUN_DATE"                    "PO_LINE_NUMBER"             
    "I0554164"                    "914100121"                   "529132260"                   "1"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "1"                          
    "I0554164"                    "914100121"                   "529137831"                   "3"                           "P0142245"                    "P0142245"                    "21-NOV-12"                   "3"                          
    ""                            "914100121"                   "529137831"                   ""                            ""                            "P0142245"                    "21-NOV-12"                   "2"                           hope that makes sense, and thanks for working with me on this.
    Edited by: mlov83 on Dec 12, 2012 5:53 AM

  • Need help with multi database query.

    Hello,
    I am working on a query between multiple databases to be view on a web app.  We have multiple web apps and we are integrating some functionality between them all into one page. 
    The data will be for a delegate someone sets for themselves (they can have more then one also).  I need a way to pull the data view it as follows.
    User, UserNumber, DelegateName, ForApp, ForApp, ForApp, ForApp, ForApp, ForApp
    I have had no problem pulling the delegates themselves and which apps they are a delegate for,  but not which person they are the delegate for.
    SELECT DISTINCT
    dbo.Employee.Position_Num AS Delegate_Position, dbo.Employee.Name AS [Delegate Name],
    (CASE WHEN Hierarchy.dbo.Employee.Position_Num = CVI_Delegate.Delegate THEN 1 ELSE 0 END) AS For_CVI,
    (CASE WHEN Hierarchy.dbo.Employee.Position_Num = Travel_Delegate.Delegate THEN 1 ELSE 0 END) AS For_Travel,
    (CASE WHEN Hierarchy.dbo.Employee.Position_Num = Dept_Deposits_Delegate.Delegate THEN 1 ELSE 0 END) AS For_DeptDeposit,
    dbo.OKCorral_Delegate.For_UserRoles AS For_OkCorralUR, dbo.OKCorral_Delegate.For_FiscalApprover AS For_OkCorralFA,
    (CASE WHEN Hierarchy.dbo.Employee.Position_Num = Reqs_Delegate.Delegate THEN 1 ELSE 0 END) AS For_Reqs
    FROM dbo.Employee LEFT OUTER JOIN
    Reqs.dbo.Delegate AS Reqs_Delegate ON dbo.Employee.Position_Num = Reqs_Delegate.Position LEFT OUTER JOIN
    DeptDeposits.dbo.Delegate AS Dept_Deposits_Delegate ON dbo.Employee.Position_Num = Dept_Deposits_Delegate.Position LEFT OUTER JOIN
    CVI.dbo.Delegate AS CVI_Delegate ON dbo.Employee.Position_Num = CVI_Delegate.Position LEFT OUTER JOIN
    dbo.OKCorral_Delegate ON dbo.Employee.Position_Num = dbo.OKCorral_Delegate.Position LEFT OUTER JOIN
    Travel.dbo.Delegate AS Travel_Delegate ON dbo.Employee.Position_Num = Travel_Delegate.Position
    This query works fine.  The problem I run into is I have to use the same Employee table to get the EmployeeName and Number
    Which will be used for both the person and the delegate.  Any ideas will be a great help.  It had been suggested I use a procedure to accomplish this, but I have no idea where to start that at.  I also have tried a nested sbu-query but since
    a person can have more then one delegate for an app,  this through errors.  Thanks.
    George Fields

    Ok,  here are the tables Travel Application Database/Delegate Table
    INSERT INTO [Travel].[dbo].[Delegate]
    ([Position]
    ,[Delegate]
    ,[StartDate]
    ,[EndDate]
    ,[CreateDate]
    ,[EditDate])
    VALUES
    (<Position, char(6),>
    ,<Delegate, char(6),>
    ,<StartDate, datetime,>
    ,<EndDate, datetime,>
    ,<CreateDate, datetime,>
    ,<EditDate, datetime,>)
    GO
    Requistions Application /Table Delegates
    INSERT INTO [Reqs].[dbo].[Delegate]
    ([Position]
    ,[Delegate]
    ,[StartDate]
    ,[EndDate]
    ,[CreateDate]
    ,[EditDate])
    VALUES
    (<Position, char(6),>
    ,<Delegate, char(6),>
    ,<StartDate, datetime,>
    ,<EndDate, datetime,>
    ,<CreateDate, datetime,>
    ,<EditDate, datetime,>)
    GO
    Heirarchy Database for Purchasing Application / Delegates Table
    INSERT INTO [Hierarchy].[dbo].[OKCorral_Delegate]
    ([Dept_Campus]
    ,[For_DeptNum]
    ,[Position]
    ,[Delegate]
    ,[StartDate]
    ,[EndDate]
    ,[CreateDate]
    ,[EditDate]
    ,[For_FiscalApprover]
    ,[For_UserRoles])
    VALUES
    (<Dept_Campus, char(2),>
    ,<For_DeptNum, char(5),>
    ,<Position, char(6),>
    ,<Delegate, char(6),>
    ,<StartDate, datetime,>
    ,<EndDate, datetime,>
    ,<CreateDate, datetime,>
    ,<EditDate, datetime,>
    ,<For_FiscalApprover, bit,>
    ,<For_UserRoles, bit,>)
    GO
    Heirarchy Database / Employee Table
    INSERT INTO [Hierarchy].[dbo].[Employee]
    ([Dept_Num]
    ,[Position_Num]
    ,[Email]
    ,[Name]
    ,[Campus]
    ,[CWID]
    ,[Student]
    ,[Employee]
    ,[OPID]
    ,[Gender]
    ,[Birth_Date])
    VALUES
    (<Dept_Num, char(5),>
    ,<Position_Num, char(6),>
    ,<Email, varchar(75),>
    ,<Name, varchar(150),>
    ,<Campus, char(2),>
    ,<CWID, varchar(16),>
    ,<Student, char(1),>
    ,<Employee, char(1),>
    ,<OPID, char(4),>
    ,<Gender, char(1),>
    ,<Birth_Date, char(8),>)
    GO
    The other two databases also have a delegate table similar to the ones above.  As you can see all information about an employee is linked by their position number in the Employee Table.
    The Position Number is used in the Position field and Delegate field of all the Delegate tables.
    I am needing to pull an employee (actually all of them) List them and then show delegates for them by which applications the delegate holds permissions too. Which is the purpose of the delegate.  So a delegate may only be a delegate for one application
    or multiple which is why I am pulling from multiple databases.
    George Fields

Maybe you are looking for

  • Mini port to HDMI not working

    Trying to connect iMac to my TV with mini port to hdmi genuine adaptor with no success. Works ok if I connect iMac to works Microsoft laptop, it displays immediately. Then connect Microsoft laptop to TV , absolutely fine. I have looked on Internet &

  • Variable Size Item, Material Setting

    Dear All, I have a requirement, from  users, They want to use Formula as ROMS1 * ROMS2 * ROMS3 * 1160  where 1160 is Density, and out put is Mass. Material Should be issued in Nos/Pc in Shop and not in KG, I want to know how this material to be used

  • How do I enable "long press" keyboard functionality on a Mac keyboard?

    I'm running FF 13 and Mac OS 10.7.4. When using other apps, I can press and hold certain keys, e.g., the letter O and a character palette appears providing me with accented/alternative characters. As I am using an American English keyboard in Germany

  • フォトブラウザ写真整理について(Photoshop Album Mini 3.0)

    フォトブラウザで表示される写真の配置(順序)を自由に変えることは出来ないのでしょうか?(ドラッグドロップなどの方法で-) 解決方法を知っている方がいらっしゃったらアドバイスをお願いします. よろしくお願いいたします.

  • Label graphics script in CS2?

    does anyone know if the LabelGraphics script for CS3 can be modified for use in IDCS2? Any hints on how to do it? Thanks jon