Subquery problem

I am trying to use a subquery where rownum =1 and have and order by to get the most recent record. If I do this:
SELECT A1,
(SELECT C1 FROM T2 WHERE C2=T1.C1 AND ROWNUM=1) AS X
FROM T1
I get a random row, so I tried this:
SELECT A1,
SELECT * FROM (SELECT C1 FROM T2 WHERE C2=T1.C1 ORDER BY C3 DESC) WHERE ROWNUM=1)) AS X
FROM T1
and I get an error saying T1.C1 is invalid. Is there a way to do this?
Thanks.

You have one opening bracket and three closing brackets. That's not a good sign ;)
The deeper problem is that a subquery cannot refer to its grandparent; e.g. this is OK:
SELECT dummy
     , ( SELECT t1.dummy
         FROM   ( SELECT dummy c1
                  FROM   dual
                  WHERE  dummy = 'X'  -- uncorrelated
                  ORDER  BY dummy DESC )
         WHERE  rownum = 1 ) AS x
FROM  dual t1;but this is not:
SELECT dummy
     , ( SELECT t1.dummy
         FROM   ( SELECT dummy c1
                  FROM   dual
                  WHERE  dummy = t1.dummy
                  ORDER  BY dummy DESC )
         WHERE  rownum = 1 ) AS x
FROM  dual t1;
ERROR at line 5:
ORA-00904: "T1"."DUMMY": invalid identifier

Similar Messages

  • Subquery problems with ordering data

    I need to order my data by an index. But I am pulling the data from three different tables and I'm new to SQL and using someone else's query. His original query is:
    WITH subquery AS
    (SELECT t1.smpl_dte, t1.pv_id,
    t1.integ_over_val
    FROM diag.blm_acct t1
    WHERE smpl_dte BETWEEN to_date('start', 'MM-DD-
    YYYY HH:MI:SS AM')
    AND to_date('end', 'MM-DD-YYYY HH:MI:SS AM'))
    SELECT t2.sgnl_id,
    SUM(subquery.integ_over_val) sumval
    FROM diag.pv_sgnl_id_assc t2,
    subquery
    WHERE t2.pv_id = subquery.pv_id
    AND sgnl_id IN(PVS)
    GROUP BY t2.sgnl_id
    In this query 'start' and 'end' are dates. PVS is a placeholder for a list of strings (see modified query below). This returns two columns, one of Strings, the other of floats. But I also need a third column which has the index of the item. The index is located in a separate table called diag.series_sgnl_rec_asgn which has three fields series_id(String), sgnl_id(String), and disp_ord_nbr (number). The sgnl_id is the same as that returned by the first query. I need to pull out all the sgnl_ids from this table that are equal to some series_id.
    Here was my attempt to get the index (disp_ord_nbr) into the results:
    WITH subquery AS
    (SELECT t1.smpl_dte, t1.pv_id,
    t1.integ_over_val
    FROM diag.blm_acct t1
    WHERE smpl_dte BETWEEN to_date('09/01/2008 12:00:00 AM', 'MM-DD-
    YYYY HH:MI:SS AM')
    AND to_date('09/02/2008 12:00:00 AM', 'MM-DD-YYYY HH:MI:SS AM')
    SELECT t2.sgnl_id,
    ser.disp_ord_nbr,
    SUM(subquery.integ_over_val) sumval
    FROM diag.pv_sgnl_id_assc t2,
    diag.series_sgnl_rec_asgn ser
    WHERE t2.pv_id = subquery.pv_id
    AND ser.disp_ord_nbr = 'Series11'
    AND t2.sgnl_id IN('Ring_Diag:BLM_A11c:Slow60PulsesTotalLoss',
    'Ring_Diag:BLM_A11d:Slow60PulsesTotalLoss', 'Ring_Diag:BLM_A11e:Slow60PulsesTotalLoss',
    'Ring_Diag:BLM_A13:Slow60PulsesTotalLoss', 'Ring_Diag:BLM_A13b:Slow60PulsesTotalLoss',
    'Ring_Diag:BLM_B01:Slow60PulsesTotalLoss', 'Ring_Diag:BLM_B02:Slow60PulsesTotalLoss',
    'Ring_Diag:BLM_B03:Slow60PulsesTotalLoss', 'Ring_Diag:BLM_B04:Slow60PulsesTotalLoss')
    GROUP BY t2.sgnl_id
    Any help would be greatly appreciated!
    Thanks.

    Try this:
    SELECT t2.sgnl_id,
           SUM(subquery.integ_over_val) sumval
      FROM diag.pv_sgnl_id_assc t2,
           diag.series_sgnl_rec_asgn ser,
          (SELECT t1.smpl_dte,
                  t1.pv_id,
                  t1.integ_over_val
             FROM diag.blm_acct t1
            WHERE smpl_dte BETWEEN to_date('09/01/2008 12:00:00 AM',    'MM-DD-YYYY HH:MI:SS AM')
                               AND to_date('09/02/2008 12:00:00 AM',    'MM-DD-YYYY HH:MI:SS AM')) subquery
    WHERE t2.pv_id         = subquery.pv_id
       AND t2.sgnl_id       = ser.sgnl_id
       AND ser.disp_ord_nbr = 'Series11'
       AND t2.sgnl_id IN('Ring_Diag:BLM_A11c:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_A11d:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_A11e:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_A13:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_A13b:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_B01:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_B02:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_B03:Slow60PulsesTotalLoss',  
                         'Ring_Diag:BLM_B04:Slow60PulsesTotalLoss')
    GROUP BY t2.sgnl_id;

  • MySQL 4.1 SubQuery Problem

    Hello,
    I switched from MySQL 4.0.x to 4.1.x to have subquery support.
    It seems to work but it looks like that the kodo generated sql
    code misses the derived table name for a "count(*)" query.
    It produces this which does not work :
    SELECT COUNT(?) FROM
    SELECT DISTINCT t0.ID AS t0_ID FROM customer t0 INNER JOIN
    custo_advertiser t1 ON t0.ID = t1.ID WHERE
    (t1.ELEMENT = ? AND t0.MAINNETWORK = ? AND t0.SUBNETWORK = ?)
    ErrorMessage : kodo.util.UserException:
    com.solarmetric.jdbc.ReportingSQLException: Syntax error or access
    violation, message from server: "Every derived table must have its own
    alias" {prepstmnt 29234933 SELECT COUNT(?) FROM (SELECT DISTINCT t0.ID AS
    t0_ID FROM customer t0 INNER JOIN custo_advertiser t1 ON t0.ID = t1.ID
    WHERE (t1.ELEMENT = ? AND t0.MAINNETWORK = ? AND t0.SUBNETWORK = ?))
    [reused=0]} [code=1248, state=42000]
    This code works after I added name for the derived table result :
    SELECT COUNT(*) FROM
    SELECT DISTINCT t0.ID AS t0_ID FROM customer t0
    INNER JOIN custo_advertiser t1 ON t0.ID = t1.ID
    WHERE (t1.ELEMENT = 6 AND t0.MAINNETWORK = 36 AND t0.SUBNETWORK = 1)
    ) derived_table_name
    Is there a way to get kodo to add the derived table name?
    Regards,
    Mark

    Mark wrote:
    That is what MySql has on their page about this issue :
    http://dev.mysql.com/doc/mysql/en/Unnamed_views.html
    Regards,
    Mark
    Hello,
    I switched from MySQL 4.0.x to 4.1.x to have subquery support.
    It seems to work but it looks like that the kodo generated sql
    code misses the derived table name for a "count(*)" query.
    It produces this which does not work :
    SELECT COUNT(?) FROM
    SELECT DISTINCT t0.ID AS t0_ID FROM customer t0 INNER JOIN
    custo_advertiser t1 ON t0.ID = t1.ID WHERE
    (t1.ELEMENT = ? AND t0.MAINNETWORK = ? AND t0.SUBNETWORK = ?)
    ErrorMessage : kodo.util.UserException:
    com.solarmetric.jdbc.ReportingSQLException: Syntax error or access
    violation, message from server: "Every derived table must have its own
    alias" {prepstmnt 29234933 SELECT COUNT(?) FROM (SELECT DISTINCT t0.ID AS
    t0_ID FROM customer t0 INNER JOIN custo_advertiser t1 ON t0.ID = t1.ID
    WHERE (t1.ELEMENT = ? AND t0.MAINNETWORK = ? AND t0.SUBNETWORK = ?))
    [reused=0]} [code=1248, state=42000]
    This code works after I added name for the derived table result :
    SELECT COUNT(*) FROM
    SELECT DISTINCT t0.ID AS t0_ID FROM customer t0
    INNER JOIN custo_advertiser t1 ON t0.ID = t1.ID
    WHERE (t1.ELEMENT = 6 AND t0.MAINNETWORK = 36 AND t0.SUBNETWORK = 1)
    ) derived_table_name
    Is there a way to get kodo to add the derived table name?
    Regards,
    Mark

  • Query, subquery problem??.. SOS...

    I've some trouble with this:
    I've got 4 tables
    LIVE
    id
    name
    street
    city
    WORK
    id
    comp_id
    sal
    LOCATED_IN
    com_id
    name
    city
    financial_group
    SUPERVISE
    id
    supervisor_id
    now, the problem:
    Lets say an XYZ financial group has companies located in different cities. I need to get all the companies from all others financial groups that have companies on all the cities where XYZ is present, For example if XYZ is present in LA, NY and SF, I need to get all the financial groups that have companies on all these cities as well even if they had companies in others citites besides these 3.
    i've tried many ways but couldnt get to it yet. Appreciate any help. THANKS!!!!!

    yeah matching up the column names... so it would be
    LIVE
    id (pk)
    name
    street
    city (fk)
    WORK
    id (pk)(fk)
    comp_id (fk)
    sal
    LOCATED_IN
    comp_id (pk)(fk)
    name
    city (fk)
    financial_group
    SUPERVISE
    id (pk)(fk)
    supervisor_id

  • Scalar Correlated Subquery Problem

    SELECT a.unit_id
    , NVL((
    SELECT COUNT(*)
    FROM (
    SELECT b.unit_id
    , b.rfq_id
    , b.vendor_id
    FROM RFQ_DISPATCHED b
    WHERE b.unit_id a.unit_id
    AND b.vendor_id = a.vendor_id
    AND b.rfq_id = a.rfq_id
    GROUP BY a.business_unit, a.rfq_id, a.vendor_id)),0) AS bid_qty
    FROM rfq_disp_hdr a
    WHERE a.unit_id = '00021'
    Oracle won't let me do this. Is it because it's correlated to a Query View? I know I can just create a view as a work around and then do a select on the view but any other suggestions on how to handle it?
    Thanks all!!

    Hi,
    Damorgan is right; whenever you have a question, you should post:
    (1) The version of Oracle (and any other relevant software) you're using
    (2) A little sample data (just enough to show what the problem is) from all the relevant tables
    (3) The results you want from that data, and an explanation of how you get from the data to the results
    (4) Your best attempt so far (formatted) (You posted this, but since it's unformated, it's very hard to read.)
    (5) The full error message (if any), including line number
    Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
    If you can present your problem using commonly available tables (for example, tables in scott schema, or views in the data dictionary), then you can omit (2).
    Formatted tabular output is okay for (3). Type these 6 characters:
    {code}
    (small letters only, inside curly brackets) before and after formatted text, to preserve spacing.
    You've been using this forum longer than I have; you should know this by now.
    It looks like the immediate problem is that you're trying to correlate a sub-query to its grandparent, not its parent. That is, the scalar sub-query could be correlated to the main query (its parent), and the in-line view could be corellated to the scalar sub-query (its parent), but the in-line view can not be correlated to the main query.
    Why are you using an in-line view? It looks like what you're trying to do is:
    SELECT      a.unit_id
    ,      NVL ( (
              SELECT        COUNT(*)
              FROM        RFQ_DISPATCHED b
              WHERE        b.unit_id a.unit_id
              AND        b.vendor_id     = a.vendor_id
              AND        b.rfq_id      = a.rfq_id
              GROUP BY  a.business_unit
              ,       a.rfq_id
              ,       a.vendor_id
             , 0
             ) AS bid_qty
    FROM      rfq_disp_hdr      a
    WHERE      a.unit_id      = '00021'but I think if correct this error, you'll just get another one. GROUPing by correlated values is very suspicious. So is doing a GROUP BY in a scalar sub-query like you're doing.
    If you really want to solve this problem, you'll have to post the information requested.

  • Problem creating a table with a subquery and a dblink

    Hello!!
    I have a little problem. When I create a table with a subquery and a dblink, for example:
    CREATE TABLE EXAMPLE2 AS SELECT * FROM EXAMPLE1@DBLINK
    the table definition is changed. Fields with a type of CHAR or VARCHAR2 are created with a size three times bigger than the original table in the remote database. Field of type DATE and NUMBER are not changed. For example if the original table, in the database 1, has a field of type CHAR(1) it is create in the local database with a type of CHAR(3), and a VARCHAR2(5) field is created with VARCHAR2(15).
    Database 1 has a WE8DEC character set.
    Database 2 has a AL32UTF8 character set.
    Could it be related to the difference in character sets?
    What can I do to make Oracle use the same table definition when creating a table in this way?
    Thanks!!

    That is related to character sets, and probably necessary if you want all the data in the remote table to be able to fit in the new table.
    When you declare a column VARCHAR2(5), by default, you're allocating 5 bytes of storage. In a single-byte character set, which I believe WE8DEC is, that also happens to equate to 5 characters. In a multi-byte character set like AL32UTF8, though, 1 character may require up to 3 bytes of storage, so you'd need to allocate 15 bytes to store that data. That's what's going on here.
    You could still store all the data if you create the table locally by explicitly requesting 5 characters of storage by declaring the column VARCHAR2(5 CHAR). You could also set the NLS_LENGTH_SEMANTICS parameter to CHAR rather than BYTE before creating the table, but I believe that both of these will only apply when you're explicitly defining columns as part of your CREATE TABLE. I don't believe either will apply to CTAS statements.
    Justin

  • Table Scope problem in subquery

    I am trying to execute following update query:
    UPDATE STG DAST     
         SET TRAVEL_COUNTRY = (SELECT TRAVEL_COUNTRY_FULL
    FROM (SELECT TRAVEL_COUNTRY_FULL,
    RANK() OVER(PARTITION BY A.PERSON_ID ORDER BY A.LAST_UPDATE_DATE DESC, A.LOC_START_DATE DESC, A.LOC_END_DATE ASC) RANK
    FROM APPS.TCS_MIS_EIT_LOCATION_EX A
    WHERE A.PERSON_ID = DAST.PERSON_ID
    AND A.TRAVEL_TYPE = 'S'
    AND '01-Nov-2011' BETWEEN A.EFFECTIVE_START_DATE AND A.EFFECTIVE_END_DATE
    AND '01-Nov-2011' BETWEEN A.LOC_START_DATE AND A.LOC_END_DATE )
    WHERE RANK = 1);
    This is giving error as "*DAST.PERSON_ID* : invalid identifier".
    But PERSON_ID is a column in STG table. As far as I know table in the outer subquery will be visible in the howsoever inner subquery. But here there seems some problems. Kindly help me solve this .

    UPDATE  STG DAST
       SET  TRAVEL_COUNTRY = (
                              SELECT  MAX(TRAVEL_COUNTRY_FULL) KEEP(DENSE_RANK FIRST ORDER BY A.LAST_UPDATE_DATE DESC,A.LOC_START_DATE DESC,A.LOC_END_DATE ASC)
                                FROM  APPS.TCS_MIS_EIT_LOCATION_EX A
                                WHERE A.PERSON_ID = DAST.PERSON_ID
                                  AND A.TRAVEL_TYPE = 'S'
                                  AND DATE '2011-11-01' BETWEEN A.EFFECTIVE_START_DATE AND A.EFFECTIVE_END_DATE
                                  AND DATE '2011-11-01' BETWEEN A.LOC_START_DATE AND A.LOC_END_DATE
                             );SY.

  • Still problem with single-row subquery returns more than one row

    //i did join each table but query runs forever and fail. looks Cartesian join so comes up the following SQL
    the following query has a problem. would you please help me, please
    Select pe.expense_id
    ,PE.CODE
    ,PE.PROJECT_ID
    ,PE.LDATE
    ,PE.INAMOUNT pe_amount
    ,(SELECT TRX.INV_AMOUNT FROM TRXEXPENSES TRX
    WHERE PE.EXPENSE_ID=TRX.EXPENSE_ID) AS invamount
    ,(SELECT RE.AMOUNT FROM REEXPENSES RE WHERE
    PE.EXPENSE_ID=RE.EXPENSE_ID) AS recogamount
    ,(SELECT MLE.M_AMOUNT FROM MATEXPENSES MLE
    WHERE PE.EXPENSE_ID=MLE.EXPENSE_ID) AS matamount
    from EXPENSES PE
    where pe.expense_id=5600
    group by expense_id,CODE,PROJECT_ID,LDATE,inamount
    //get error message
    ora-01427:single-row subquery returns more than one row
    //check database
    select expense_id,count(*) from TRXEXPENSES
    where expense_id in(select expense_id from
    expenses)
    group by expense_id
    having count(*)>1
    //here is duplicate record a lot
    EXPENSE_ID     COUNT(*)
    4176     2
    5600     3
    9572     2
    9573     2
    9574     2

    Yes, Expense_id has so many returning rows for trx.inv_amount from trxexpenses in subquery.
    I want to show Expense_id with retruning rows using the above query.
    ex)The result of the query is like that;
    Expense_ Id project_id Ldate InvAmount RecogAmount MatAmount
    5600 123 3/2/02 $100(InvAmount)
    5600 432 3/12/02 $200(recogAmount)
    5600 432 4/12/02 $250(MatAmount)
    Thank you so much
    Message was edited by:
    user524064
    Message was edited by:
    user524064

  • Connect by prior subquery - performance problem

    Hello,
    I have some data which is organized in a folder tree. The requeriement is to be able to search from any subfolder and down.
    /Documents
    ___Folder A
    ______Doc A
    ______Doc B
    ___Folder B
    ______Doc C
    ______Doc D
    The folder structure is defined in a table called CORNERS where the records(=folders) has a ID/PARENTID relationsship to describe the folder structure.
    Another table, called MASTER, contains the main content. Each item has a CORNERID value which defined in which subfolder the document is located.
    MASTER
    ID CORNERID TITLE INDEX_URL
    100 2 Doc A http://xxx/yy.com
    101 2 Doc B http://xxz/yy.com
    102 3 Doc C http://xyz/yy.com
    103 3 Doc D http://xyz/zz.com
    CORNERS
    ID PARENTID NAME
    1 Documents
    2 1 Folder A
    3 1 Folder B
    MASTER table has ~50000 records
    CORNERS has ~900 records.
    Analyzed nighly and stats are fresh.
    Indexes defined:
    CORNERS_ID_PARENT_IDX corners(id,parentid)
    CORNERS_PARENT_ID_IDX corners(parentid,id)
    MASTER_ID_CORNERID_IDX master(id,cornerid)
    MASTER_CORNERID_ID_IDX master(cornerid,id)
    Oracle Text index (URL based) on MASTER.INDEX_URL
    Foreign key defined:
    MASTER.CORNERID references CORNERS.ID
    If I do a search without involving the hierarchy, then the search runs pretty fast:
    SQL> SELECT COUNT(*) FROM (SELECT a.id, a.cornerid FROM MASTER a WHERE (CONTAINS(title,'$ADS AND {S} AND $PARAMETER',2) > 1 OR CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1) );
    COUNT(*)
    5125
    Elapsed: 00:00:00.14
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1354 Card=1 Bytes=15
    8)
    1 0 SORT (AGGREGATE)
    2 1 TABLE ACCESS (BY INDEX ROWID) OF 'MASTER' (Cost=1354 Car
    d=758 Bytes=119764)
    3 2 BITMAP CONVERSION (TO ROWIDS)
    4 3 BITMAP OR
    5 4 BITMAP CONVERSION (FROM ROWIDS)
    6 5 SORT (ORDER BY)
    7 6 DOMAIN INDEX OF 'MASTER_TITLE_IDX' (Cost=470)
    8 4 BITMAP CONVERSION (FROM ROWIDS)
    9 8 SORT (ORDER BY)
    10 9 DOMAIN INDEX OF 'MASTER_IDX' (Cost=650)
    Statistics
    1462 recursive calls
    0 db block gets
    5507 consistent gets
    347 physical reads
    0 redo size
    380 bytes sent via SQL*Net to client
    503 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    2 sorts (memory)
    0 sorts (disk)
    1 rows processed
    SQL>
    BUT, if I add a subquery to limit the search to a certain folder tree (which includes ~200 nodes), then the performance is really badly affected. The subquery itself runs fast - around 0.07 seconds, but together with the rest of the query the preformance is really bad:
    SQL> SELECT COUNT(*) FROM (SELECT a.id, a.cornerid FROM MASTER a WHERE (CONTAINS(title,'$ADS AND {S} AND $PARAMETER',2) > 1 OR CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1) AND cornerid IN ( SELECT ID FROM corners START WITH id = 2434 CONNECT BY PRIOR id = parentid) );
    COUNT(*)
    942
    Elapsed: 00:00:01.83
    Execution Plan
    0 SELECT STATEMENT Optimizer=CHOOSE (Cost=118 Card=1 Bytes=175
    1 0 SORT (AGGREGATE)
    2 1 TABLE ACCESS (BY INDEX ROWID) OF 'MASTER' (Cost=19 Card=
    1 Bytes=162)
    3 2 NESTED LOOPS (Cost=118 Card=8 Bytes=1400)
    4 3 VIEW OF 'VW_NSO_1' (Cost=2 Card=6 Bytes=78)
    5 4 SORT (UNIQUE)
    6 5 CONNECT BY (WITH FILTERING)
    7 6 NESTED LOOPS
    8 7 INDEX (UNIQUE SCAN) OF 'SYS_C002969' (UNIQUE
    ) (Cost=1 Card=1 Bytes=4)
    9 7 TABLE ACCESS (BY USER ROWID) OF 'CORNERS'
    10 6 NESTED LOOPS
    11 10 BUFFER (SORT)
    12 11 CONNECT BY PUMP
    13 10 INDEX (RANGE SCAN) OF 'CORNERS_PARENT_ID_IDX
    ' (NON-UNIQUE) (Cost=2 Card=6 Bytes=48)
    14 3 INDEX (RANGE SCAN) OF 'MASTER_CORNERID_ID_IDX' (NON-
    UNIQUE) (Cost=1 Card=38)
    Statistics
    29267 recursive calls
    0 db block gets
    55414 consistent gets
    140 physical reads
    0 redo size
    380 bytes sent via SQL*Net to client
    503 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    12 sorts (memory)
    0 sorts (disk)
    1 rows processed
    I've tried an alternative syntax, instead of the IN clause like this:
    SELECT COUNT(*) FROM (
    WITH folders AS (
    SELECT ID
    FROM CORNERS
    START WITH ID=2434
    CONNECT BY PRIOR ID= PARENTID
    SELECT a.id
    FROM MASTER a, folders b
    WHERE a.cornerid = b.id
    AND CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1);
    It does runfaster, but still takes around 1 second.
    Any suggestion on how to make this run faster!?
    Thanks in advance!
    -Mats

    how long does it takes to complete the query?

  • URGENT!Problem running a Query with a Subquery that includes the same table

    Hello all,
    Currently we are working over Oracle Database 10g Release 2 (10.2.0.3) Patch Set1.
    We have registered a schema called ICRI and we have created two VIEW over this schema to work in some occasions.
    CREATE OR REPLACE VIEW "ICRI_RELACIONAL_VIEW"
    (IDICRI, NOMBRERECURSO, VERSIONRECURSO) AS
    SELECT extractValue(value(i), '/ICRI/ID/text()'),
           extractValue(value(i), '/ICRI/NombreRecurso/text()'),
           extractValue(value(i), '/ICRI/VersionRecurso/text()') || '.' || extractValue(value(m), '/Modificacion/Secuencia/text()'),
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Modificacion'))) m
    WHERE extractValue(value(m), '/Modificacion/Secuencia/text()') =
          (SELECT max(extractValue(value(s), '/Secuencia/text()'))
           FROM table(xmlsequence(extract(value(i),'/ICRI/Modificaciones/Modificacion/Secuencia'))) s)
    WITH READ ONLY;
    CREATE OR REPLACE VIEW "ICRI_DOMINIOS_VIEW"
    (ID, DOMINIO) AS
    SELECT extractValue(value(i), '/ICRI/ID/text()'),
           extractValue(value(a), '/Dominio/text()', 'xmlns="http://www.orswegimoarmada.es/ORSWE/ICRI"')
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Dominios/Dominio'))) a
    WITH READ ONLY;We have created 5000 XML documents based in this schema and stored in the database.
    Now we have executed different querys to obtain certain data.
    * QUERY 1
    SELECT COUNT(*) FROM ICRI_DOMINIOS_VIEW V1, ICRI_DOMINIOS_VIEW V2
    WHERE V1.ID = V2.ID AND V1.DOMINIO = 'Mar' AND V2.DOMINIO = 'Tierra'Time: 38sg. 1 row, Value: 1097.
    * QUERY 2
    SELECT COUNT(*) FROM ICRI_DOMINIOS_VIEW V1
    WHERE V1.DOMINIO = 'Mar'
          AND
          V1.ID IN (SELECT V2.ID FROM ICRI_DOMINIOS_VIEW V2
                    WHERE V2.DOMINIO = 'Tierra')Time: 34sg. 1 row, Value: 1097.
    * QUERY 3 (XPath Version)
    SELECT COUNT(*)
    FROM ICRI
    WHERE existsNode(object_value, '/ICRI/Dominios[Dominio="Mar" and Dominio="Tierra"]')=1
    Time: 32msg. 1 row, Value: 1097.
    * QUERY 4 (Version XPath)
    SELECT extractValue(object_value, '/ICRI/ID/text()')
    FROM ICRI
    WHERE existsNode(object_value, '/ICRI/Dominios[Dominio="Mar" and Dominio="Tierra"]')=1
    Time: 63mseg. 1097 rows.
    * QUERY 5
    SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1, ICRI_DOMINIOS_VIEW V2
    WHERE V1.ID = V2.ID AND V1.DOMINIO = 'Mar' AND V2.DOMINIO = 'Tierra'
    Time: 15sg. 1097 rows.
    * QUERY 6
    SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1
    WHERE V1.DOMINIO = 'Mar'
    AND
    V1.ID IN (SELECT V2.ID FROM ICRI_DOMINIOS_VIEW V2
    WHERE V2.DOMINIO = 'Tierra')
    Time: 26sg. 1097 rows.
    Now, with the next query, we have found an important issue in Oracle, because this query doesn't return any row.
    * QUERY 7
    SELECT extractValue(value(i), '/ICRI/ID/text()') ID,
           extractValue(value(i), '/ICRI/NombreRecurso/text()') NOMBRE,
           extractValue(value(i), '/ICRI/VersionRecurso/text()') || '.' || extractValue(value(m), '/Modificacion/Secuencia/text()') VERSION
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Modificacion'))) m
    WHERE
       (extractValue(value(m), '/Modificacion/Secuencia/text()') =
        (SELECT max(extractValue(value(s), '/Secuencia/text()'))
         FROM table(xmlsequence(extract(value(i),'/ICRI/Modificaciones/Modificacion/Secuencia'))) s)
    AND
       (extractValue(value(i), '/ICRI/ID/text()') IN
        (select extractValue(object_value, '/ICRI/ID/text()') ID
         FROM ICRI
         WHERE (existsNode(object_value, '/ICRI/Dominios[Dominio="Mar" and Dominio="Tierra"]')=1)
    )Time 607mseg. 0 rows.
    * QUERY 8
    SELECT VI.IDICRI, VI.NOMBRERECURSO, VI.VERSIONRECURSO
    FROM ICRI_RELACIONAL_VIEW VI, (SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1, ICRI_DOMINIOS_VIEW V2
                                   WHERE V1.ID = V2.ID AND V1.DOMINIO = 'Mar' AND V2.DOMINIO = 'Tierra') V3
    WHERE VI.IDICRI = V3.ID Time: 16sg. 1097 rows.
    * QUERY 9
    SELECT VI.IDICRI, VI.NOMBRERECURSO, VI.VERSIONRECURSO
    FROM ICRI_RELACIONAL_VIEW VI
    WHERE VI.IDICRI IN
    (SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1
    WHERE V1.DOMINIO = 'Mar'
          AND
          V1.ID IN (SELECT V2.ID FROM ICRI_DOMINIOS_VIEW V2
                    WHERE V2.DOMINIO = 'Tierra')Time: 34 sg. 1097 rows.
    * QUERY 10
    SELECT extractValue(value(i), '/ICRI/ID/text()') ID,
    extractValue(value(i), '/ICRI/NombreRecurso/text()') NOMBRE,
    extractValue(value(i), '/ICRI/VersionRecurso/text()') || '.' || extractValue(value(m), '/Modificacion/Secuencia/text()') VERSION
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Modificacion'))) m,
    (SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1, ICRI_DOMINIOS_VIEW V2
    WHERE V1.ID = V2.ID AND V1.DOMINIO = 'Mar' AND V2.DOMINIO = 'Tierra') V3
    WHERE
    (extractValue(value(m), '/Modificacion/Secuencia/text()') =
    (SELECT max(extractValue(value(s), '/Secuencia/text()'))
    FROM table(xmlsequence(extract(value(i),'/ICRI/Modificaciones/Modificacion/Secuencia'))) s)
    AND
    extractValue(value(i), '/ICRI/ID/text()') = V3.ID
    Time: 15sg. 1097 rows.
    * QUERY 11
    SELECT extractValue(value(i), '/ICRI/ID/text()') ID,
           extractValue(value(i), '/ICRI/NombreRecurso/text()') NOMBRE,
           extractValue(value(i), '/ICRI/VersionRecurso/text()') || '.' || extractValue(value(m), '/Modificacion/Secuencia/text()') VERSION
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Modificacion'))) m
    WHERE
       (extractValue(value(m), '/Modificacion/Secuencia/text()') =
        (SELECT max(extractValue(value(s), '/Secuencia/text()'))
         FROM table(xmlsequence(extract(value(i),'/ICRI/Modificaciones/Modificacion/Secuencia'))) s)
    AND
       (extractValue(value(i), '/ICRI/ID/text()') IN (SELECT V1.ID FROM ICRI_DOMINIOS_VIEW V1
                                                      WHERE V1.DOMINIO = 'Mar'
                                                      AND
                                                      V1.ID IN (SELECT V2.ID FROM ICRI_DOMINIOS_VIEW V2
                                                                WHERE V2.DOMINIO = 'Tierra'))
    )Time: 30sg. 1097 rows.
    * QUERY 12
    SELECT extractValue(value(i), '/ICRI/ID/text()') ID,
           extractValue(value(i), '/ICRI/NombreRecurso/text()') NOMBRE,
           extractValue(value(i), '/ICRI/VersionRecurso/text()') || '.' || extractValue(value(m), '/Modificacion/Secuencia/text()') VERSION
    FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Modificacion'))) m
    WHERE
       (extractValue(value(m), '/Modificacion/Secuencia/text()') =
        (SELECT max(extractValue(value(s), '/Secuencia/text()'))
         FROM table(xmlsequence(extract(value(i),'/ICRI/Modificaciones/Modificacion/Secuencia'))) s)
       )Time: 187msg. 5000 rows.
    Well, if we execute the query based in a relational view all work fine but the performance of the query is hugely decreased. If we try to execute the query based in the XPath values, this options must be the correct, the query doesn't return any result.
    Any idea to solve this problem? For us it is very important to find a solution as soon as possible, because our development time is finishing.
    Our clients have installed Oracle Client 10.2.0.1 & ODAC 10.2.0.20.
    Thanks in advance for your help,
    David.

    SQL> alter session set optimizer_features_enable='10.1.0';
    Session altered.
    SQL> SELECT count(*)
    2 FROM ICRI i, table(xmlsequence(extract(value(i), '/ICRI/Modificaciones/Mo
    dificacion'))) m
    3 WHERE
    4 extractValue(value(i), '/ICRI/ID/text()') IN
    5 (select extractValue(object_value, '/ICRI/ID/text()') ID
    6 FROM ICRI
    7 WHERE (existsNode(object_value,
    8 '/ICRI/Dominios[Dominio="Mar" and Dominio="Tierra"]')=1))
    9 /
    COUNT(*)
    5
    Test this with a few of your queries and see if the results are expected.
    if so I am thinking it is close to bug 5585187
    QUERY NOT RETURNING PROPER RESULTS WITH INLINE VIEWS
    Fixed in 11.
    I am going to see if I can get an env to see if your TC works with this fix before I confirm it 100 percent.
    Also note this was done with a very scaled down version of your testcase. Using only one XML doc
    regards
    Coby
    Message was edited by: Coby
    coadams

  • Problem with subquery

    Hi all
    I'm having problem with select statement .I want to return only one row of data having the ealiest serv_start_date,latest serv_end_date and smallest ref_no.This is my data:
    ACCT_NO CHILD_ACCT_NO SERV_STAR SERV_END_ SERV_NO
    X700026640404 X700143120108 06-JUL-05 31-DEC-06 10268947
    X700026640404 X700143120207 01-JUN-05 05-APR-06 10268949
    X700026640404 X700143120306 01-JUN-05 05-APR-06 10268950
    X700026640404 X700143120405 01-JUN-05 05-APR-06 10268951
    X700026640404 X700143120504 01-JUN-05 05-APR-06 10268952
    X700026640404 X700143120603 01-JUN-05 05-APR-06 10268953
    X700026640404 X700143120702 01-JUN-05 05-APR-06 10268954
    X700026640404 X700143120801 01-JUN-05 05-APR-06 10268955
    X700026640404 X700143120910 06-JUL-05 31-DEC-06 10268956
    X700026640404 X700143121205 19-AUG-05 31-DEC-06 14900166
    so as u can see,the earlist start_date is '01-JUN-05' and contains 7 rows of it.Then i need to check the latest serv_end_date for each 7 rows and it's all the same,then i need to check the smallest serv_no of the 7 rows which is 10268949
    So i need to return only this row
    ACCT_NO CHILD_ACCT_NO SERV_STAR SERV_END_ SERV_NO
    X700026640404 X700143120207 01-JUN-05 05-APR-06 10268949
    How to solve it?
    Please help...tq in advance

    Does this satisfy your requirement?
    SQL> SELECT   ACCT_NO, SERV_START, MIN (SeRV_END_DT), MIN (SERV_NO)
        FROM (SELECT 'X700026640404' ACCT_NO, 'X700143120108' CHILD_ACCT_NO, '06-JUL-05' SERV_START,
                     '31-DEC-06' SERV_END_DT, '10268947' SERV_NO
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120207', '01-JUN-05', '05-APR-06', '10268949'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120306', '01-JUN-05', '05-APR-06', '10268950'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120405', '01-JUN-05', '05-APR-06', '10268951'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120504', '01-JUN-05', '05-APR-06', '10268952'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120603', '01-JUN-05', '05-APR-06', '10268953'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120702', '01-JUN-05', '05-APR-06', '10268954'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120801', '01-JUN-05', '05-APR-06', '10268955'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143120910', '06-JUL-05', '31-DEC-06', '10268956'
                FROM DUAL
              UNION
              SELECT 'X700026640404', 'X700143121205', '19-AUG-05', '31-DEC-06', '14900166'
                FROM DUAL) DATA
    GROUP BY acct_no, serv_start;
    ACCT_NO       SERV_STAR MIN(SERV_ MIN(SERV
    X700026640404 01-JUN-05 05-APR-06 10268949
    X700026640404 06-JUL-05 31-DEC-06 10268947
    X700026640404 19-AUG-05 31-DEC-06 14900166Edit: Please use PL/SQL for such questions.

  • Problem framing sql subquery...

    Hi there!
    I wrote the below query to give me results from a table which contains:
    The most recent time (max(sessionDate)) from the visits made by the user(tom) to the learningObject(lo_1,...lo_n) in a package(SingleCourseEx).
    //query - 1
    String query = SELECT test.STUDENT_ID,test.LEARNING_OBJECT_NAME,MAX(test.SESSION_DATE) FROM SESSION AS test WHERE test.PACKAGE_ID='SingleCourseEx' And test.STUDENT_ID='tom' GROUP BY test.LEARNING_OBJECT_NAME,test.STUDENT_ID
    this query gives me proper results:
    tom: Conduct of Vessels in Sight of One Another : 2003-01-07 12:00:36
    tom: Exam : 2003-01-07 12:10:33
    tom: Lights & Shapes : 2003-01-07 12:12:45
    Now I want to get the other details(sessionID) of that rows which are unique (that means I cant ask for them in my above query as they are aggregated)
    So I wrote the below query(using my query-1 as a subquery)and it doesn't work the way I wanted..
    results are:
    tom:4:Conduct of Vessels in Sight of One Another : 2003-01-07 12:00:36
    tom:24:Conduct of Vessels in Sight of One Another : 2003-01-04 10:00:36
    tom:2:Exam : 2003-01-07 12:10:33
    tom:26:Lights & Shapes : 2003-01-07 12:12:45
    tom:22:Exam : 2003-01-09 14:10:33
    That means it's picking up all rows :(
    Query - 2 with the above subquery
    SELECT original.STUDENT_ID,original.SESSION_ID,original.LEARNING_OBJECT_NAME,
    original.SESSION_DATE FROM SESSION AS original WHERE EXISTS (SELECT test.STUDENT_ID,test.LEARNING_OBJECT_NAME,MAX(test.SESSION_DATE) FROM SESSION AS test WHERE test.PACKAGE_ID='SingleCourseEx' And test.STUDENT_ID='tom' GROUP BY test.LEARNING_OBJECT_NAME,test.STUDENT_ID)
    I am using Access as my database.
    Any ideas on this?? Any suggestions would be of great help.
    -M

    Can somebody pls help me with my query. I tried it in so many ways and all in vein.
    All I wanted to do is:
    Select "all/rest of the columns"
    from session
    where student_id, loName, session_date matches
    the results of my sub query.
    I could use "IN" operator if the matching is only for one field, but don't know how to match multiple fields.
    Any suggestions/ideas on this would be really helpful.
    best regards,
    M

  • Subquery and procedure  - problem

    Hello,
    I have procedure created with option "WITH RESULT VIEW ProcViewTest1".
    When I try to execute statement below everything is ok.
    select * from ProcViewTest1 WITH PARAMETERS ('placeholder' = ('$$str1$$', 'Michal'))
    But when I try to execute:
    select *, (select * from ProcViewTest1 WITH PARAMETERS ('placeholder' = ('$$str1$$', 'Michal'))) as col1 from dummy
    I have error: "sql syntax error: incorrect syntax near "WITH"
    I checked that in the case of procedures without parameters can be used as a subquery.
    Why I have this message?
    What shoul I do?
    Maybe the error is in syntax?
    Best regards,

    Hello,
    I have procedure created with option "WITH RESULT VIEW ProcViewTest1".
    When I try to execute statement below everything is ok.
    select * from ProcViewTest1 WITH PARAMETERS ('placeholder' = ('$$str1$$', 'Michal'))
    But when I try to execute:
    select *, (select * from ProcViewTest1 WITH PARAMETERS ('placeholder' = ('$$str1$$', 'Michal'))) as col1 from dummy
    I have error: "sql syntax error: incorrect syntax near "WITH"
    I checked that in the case of procedures without parameters can be used as a subquery.
    Why I have this message?
    What shoul I do?
    Maybe the error is in syntax?
    Best regards,

  • Complex query/subquery/join problem

    Hi,
    i need to retrieve information from our database in one single dataset but i can't get it all together...
    Here's the situation:
    We have several linked tables:
    Workorder (wo_operation)
    -woo_key
    Workorder_task (wo_task)
    -wot_key -> PK
    -woo_key -> FK_woo
    Workorder_task_labor (wo_task_labor)
    -wtl_key -> PK
    -wot_key -> FK_wot
    -start_time -> essential field
    I'm running a query which retrieves records from the Workorder (wo_operation) table like this (this one works nicely, don't mind the other joins):
    SELECT
    rownum num,
    woo.woo_auto_key,
    woo.si_number,
    apc.application_code,
    cmp.company_name,
    woo.company_ref_number,
    view_wo.serial_number,
    view_wo.part_number,
    view_wo.description part_description,
    wos.description status_description
    FROM (((((wo_operation woo INNER JOIN view_spb_wo_maincomponent view_wo ON woo.woo_auto_key = view_wo.woo_auto_key)
    LEFT JOIN wo_status wos ON woo.wos_auto_key = wos.wos_auto_key)
    INNER JOIN parts_master pnm ON woo.pnm_auto_key = pnm.pnm_auto_key)
    INNER JOIN application_codes apc ON pnm.apc_auto_key = apc.apc_auto_key)
    INNER JOIN companies cmp ON woo.cmp_auto_key = cmp.cmp_auto_key)
    WHERE woo.wos_auto_key IS NULL OR woo.wos_auto_key not IN (2, 10)
    Now here's the problem. I need to add one more column which shows the last task (max(wo_task_labor.start_time)) that people have been working on (wo_task.description).
    Wo_task is linked to wo_operation on WOO_KEY (many TO one)
    Wo_task_labor is linked to Wo_task on WOT_KEY (zero or many TO one)
    So I need to find the MAX wo_task_labor.START_TIME and then Select the wo_task.description with that start_time. BUT since the relation is ZERO OR MORE to ONE it could be that there isn't even a START_TIME available for Max() function.......
    Is there anybody who could send me in the right direction???

    Hmmz ok, I just finished a more readable problem description.. Were you absolutely certain that my problem needs another approach?
    here's the problem again:
    Situation:
    wo_operation
    | Woo_auto_key | Si_number |
    | 1            | w100      |
    | 2            | w105      |
    | 3            | w200      |
    wo_task
    | Wot_auto_key | Woo_auto_key | Description |
    | 1            | 1            | OPENING     |
    | 2            | 1            | INSPECT     |
    | 3            | 2            | OPENING     |
    | 4            | 2            | REJECT      |
    | 5            | 3            | OPENING     |
    Wo_task_labor
    | Wtl_auto_key | Wot_auto_key | Start_time | Stop_time |
    | 1            | 1            | 7:00       | 7:05      |
    | 2            | 1            | 11:45      | 12:00     |
    | 3            | 2            | 10:00      | 10:15     |
    | 4            | 2            | 11:00      | 11:20     |
    | 5            | 2            | 11:35      | 11:40     |
    | 6            | 3            | 9:00       | 9:15      |
    | 7            | 3            | 9:30       | 9:40      |
    | 7            | 3            | 9:45       | 9:50      |
    | 8            | 4            | 9:00       | 10:00     |
    | 9            | 4            | 10:15      | 10:30     |
    Query:
    SELECT
         woo.si_number
    FROM
         wo_operation woo
    Result:
    | SI_NUMBER |
    | w100      |
    | w105      |
    | w200      |
    My needed result:
    | SI_NUMBER | DESCRIPTION      |
    | w100      | OPENING          | -> last labor is wtl_auto_key 2 from 11:45 to 12:00
    | w105      | REJECT           | -> last labor is wtl_auto_key 9 from 10:15 to 10:30
    | w200      | (null) or 'none' | -> last labor is not available since there is no labor record
    How can this be done querywise?
    Message was edited by:
    user574699

  • Where clause problem in a subquery

    I'll try to explain as detailed as possible.
    Given the following set of data and the parameters passed the query must only return one row;
    If the structure_chain is like the parameter passed, then select that row
    If not then strip out the first number in both the parameter and the column,
    e.i., '2.35364194.34889485' becomes '35364194.34889485'
    The select is what is currently in the code and so far I've not been able to get the (new) desired results - customer changed/enhanced requirements
    with TT as
        (select 1 row_no, 22794978 old_child_id, 51755902 new_child_id, '1.35364194' structure_chain from dual union all
         select 2, 22794978, 51755899, '1.23576950' from dual union all
         select 3, 17872962, 51755893, '1.23576950' from dual union all
         select 4, 17872962, 51756065, '1.35364194.34880851' from dual union all
         select 5, 17872962, 51759249, '2.35364194.34880851' from dual union all
         select 6, 17872962, 51759248, '1.23576950.22795468' from dual union all
         select 7, 17872962, 51759250, '2.23576950.22795468' from dual )
    select * from tt
    where old_child_id = &1
    and   &2 like structure_chain ||'%'
    17872962 '2.35364194.34880851'   -- Return row_no 5 
    17872962 '1.23576950.22795468'   -- Return row_no 6 - this returns more than one
    17872962 '1.35364194.34880851'   -- Return row_no 4
    17872962 '2.23576950.22795468'   -- Return row_no 7
    22794978 '2.35364194.34889485'   -- Return row_no 1 - does not return anything
    22794978 '1.35364194.34889485'   -- Return row_no 1

    Hi,
    I'm not sure what you're asking.
    It would help if you posted the results you want as clearly as you posted the sample data. For each set of parametes, post the desired result set.
    I think you want to do two kinds of pattern matches, and return the results of the strictest one that has results.
    That is, if there is a match on all parts of structure_chain, then return the rows that match all parts.
    But if there is no match on all parts of structure_chain, then return the rows (if any) that match if we ignore the sub-atring before the first dot.
    That's an example of a Top-N Query , and here's one way to do it:
    WITH     got_r_num AS
         SELECT  tt.*
         ,     DENSE_RANK () OVER (ORDER BY  CASE
                                                WHEN  '&2'        LIKE structure_chain || '%'
                                    THEN  1
                                    ELSE  2
                                            END
                           ) AS r_num
         FROM     tt
         WHERE      old_child_id     = &1
         AND        SUBSTR ( '&2'
                     , INSTR ('&2', '.')
                     )                LIKE SUBSTR ( structure_chain
                                                  , INSTR (structure_chain, '.')
                                      ) || '%'
    SELECT     row_no, old_child_id, new_child_id, structure_chain
    FROM     got_r_num
    WHERE     r_num     = 1
    ;With parameters &1=17872962 and &2=1.23576950.22795468, the query above produces this output:
    `   ROW_NO OLD_CHILD_ID NEW_CHILD_ID STRUCTURE_CHAIN
             3     17872962     51755893 1.23576950
             6     17872962     51759248 1.23576950.22795468because both rows matched the given &2, including the '1.' at the beginning. (The query you posted gave the same results in this case.)
    With parameters &1=22794978 and &2=2.35364194.34889485, the query above produces:
        ROW_NO OLD_CHILD_ID NEW_CHILD_ID STRUCTURE_CHAIN
             1     22794978     51755902 1.35364194because there was no match when considering the '2.' at the beginning of &2, but the row shown does match when we ignore the '2.'.
    The WHERE clause in the sub-query narrows the result set down to rows that meet at least the looser match reuirement.
    The CASE expression ranks each row as 1 if it meets the stricter requirement, and 2 if it only met the looser one.
    DENSE_RANK returns 1 for the lower of those numbers that was actually found.

Maybe you are looking for