Update with join and group by

Hello All,
I'm trying to update several colums of a table from a inner join query.
First a retrieve the rows afected and the values that I need for the update (I call this subquery ED_Query).
It's important to note that this subquery has a group by and and having clause.
My first attemp (using the query that work in SQL Server query) fails:
SQL> update ED_Update
2 set ED_Update.dtHoraInicioReal = ED_Query.dtHoraInicioReal,
3 ED_Update.dtHoraFinReal = ED_Query.dtHoraFinReal,
4 ED_Update.fPorcentajeRealizado = ED_Query.fPorcentajeRealizado
5 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED_Update
6 inner join (
7 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
8 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
9 MAX(HPP.iOrden) as iOrdenUltimaParada,
10 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
11 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
12 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado
13 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
14 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
15 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
16 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
17 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
18 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal
19 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
20 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
21 ) ED_Query
22 on ED_Update.iIdExpedicionDiaria = ED_Query.iIdExpedicionDiaria;
ERROR at line 5:
ORA-00933: SQL command not properly ended
The subquery (ED_Query) work fine in Oracle, so I suspect that the problems are when I mix it with the update clause.
SQL> select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
2 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
3 MAX(HPP.iOrden) as iOrdenUltimaParada,
4 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
5 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
6 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
7 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
8 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
9 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
10 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
11 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
12 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
13 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal, ED.dtHoraFinReal, ED.fPorcentajeRealizado
14 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
15 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal);
IIDEXPEDICION IIDEXPEDICIONDIARIA INUMPARADAS IORDENULTIMAPARADA DTHORAINI
DTHORAFIN FPORCENTAJEREALIZADO ED_DTHORA ED_DTHORA ED_FPORCENTAJEREALIZADO
-131076 5662 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5663 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
-131076 5664 406 15-JAN-13
15-JAN-13 15-JAN-13 15-JAN-13 0
After reading this forum, I change the query and try the next one:
SQL> UPDATE
2 (
3 select distinct ED.iIdExpedicion, ED.iIdExpedicionDiaria,
4 MAX(PT.iOrdenEnTrayecto) + 1 as iNumParadas,
5 MAX(HPP.iOrden) as iOrdenUltimaParada,
6 MIN(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60)) as dtHoraInicioReal,
7 MAX(dtHora_LlegadaReal) as dtHoraFinReal,
8 100 * cast ((MAX(HPP.iOrden) + 1) as float) / cast ((MAX(PT.iOrdenEnTrayecto) + 1) as float) as fPorcentajeRealizado,
9 ED.dtHoraInicioReal as ED_dtHoraInicioReal, ED.dtHoraFinReal as ED_dtHoraFinReal, ED.fPorcentajeRealizado as ED_fPorcentajeRealizado
10 from HISTORICOS_AVANZA.HSAE_HIS_EXPEDICIONDIARIA ED
11 left join HISTORICOS_AVANZA.HSAE_HIS_HORAPASOPARADA HPP
12 on ED.iIdExpedicion = HPP.iIdExpedicion and ED.dtJornada = HPP.dtJornada
13 left join AVANZA.SAE_URB_PARADASTRAYECTO PT on ED.iIdLinea = PT.iIdLinea and ED.iIdTrayecto = PT.iIdTrayecto
14 where ED.dtJornada = TO_DATE('14/01/2013', 'DD/MM/YYYY') and ED.iIdExpedicion in (-131076)
15 group by ED.iIdExpedicion, ED.iIdExpedicionDiaria, ED.dtHoraInicioReal,ED.dtHoraFinReal, ED.fPorcentajeRealizado
16 having ED.dtHoraInicioReal <> min(dtHora_LlegadaReal + iTiempoEnParada/(24*60*60))
17 or ED.dtHoraFinReal <> max(dtHora_LlegadaReal)
18 )
19 SET ED_dtHoraInicioReal = dtHoraInicioReal,
20 ED_dtHoraFinReal = dtHoraFinReal,
21 ED_fPorcentajeRealizado = fPorcentajeRealizado;
ERROR at line 2:
ORA-01732: data manipulation operation not legal on this view
Some help?
Thanl in advance.
Edited by: 984483 on 28-ene-2013 1:48

Thanks for your answer. I tried to rewrite my question.
SQL> select * from v$version;
BANNER
Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
PL/SQL Release 9.2.0.3.0 - Production
CORE 9.2.0.3.0 Production
TNS for 32-bit Windows: Version 9.2.0.3.0 - Production
NLSRTL Version 9.2.0.3.0 - Production
I have 2 tables. I like to update one of them (ED_Update) with the data from the another one (ED_Query).
This example is equivalent:
create table ED_Query (id number,
     date01 date,
number01 number)
insert into ED_Query values (1, to_date('01/01/2013','DD/MM/YYYY'), 10);
insert into ED_Query values (2, to_date('01/01/2013','DD/MM/YYYY'), 20);
insert into ED_Query values (3, to_date('01/01/2013','DD/MM/YYYY'), 30);
insert into ED_Query values (4, to_date('02/01/2013','DD/MM/YYYY'), 40);
insert into ED_Query values (5, to_date('03/01/2013','DD/MM/YYYY'), 50);
create table ED_Update (date01 date,
          numberMax number,
          numberSum number)
insert into ED_Update values (to_date('01/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('02/01/2013','DD/MM/YYYY'), 0, 0);
insert into ED_Update values (to_date('03/01/2013','DD/MM/YYYY'), 0, 0);     
The next update query fails with ORA-00933: SQL command not properly ended.
update ED_Update
set ED_Update.date01 = ED_Query.date01,
     ED_Update.numberMax = ED_Query.numberMax,
     ED_Update.numberSum = ED_Query.numberSum
inner join
     select date01, max (number01) as numberMax, sum(number01) as numberSum
     from ED_Query
     where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
     group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
I think the problem is in the update clause because the next query work:
select * from
ED_Update
inner join
     select date01, max (number01) as numberMax, sum(number01) as numberSum
     from ED_Query
     where date01 = TO_DATE('01/01/2013', 'DD/MM/YYYY')
     group by date01
) ED_Query
on ED_Update.date01 = ED_Query.date01
Thank in advance.

Similar Messages

  • Need help in optimizing the query with joins and group by clause

    I am having problem in executing the query below.. it is taking lot of time. To simplify, I have added the two tables FILE_STATUS = stores the file load details and COMM table that is actual business commission table showing records successfully processed and which records were transmitted to other system. Records with status = T is trasnmitted to other system and traansactions with P is pending.
    CREATE TABLE FILE_STATUS
    (FILE_ID VARCHAR2(14),
    FILE_NAME VARCHAR2(20),
    CARR_CD VARCHAR2(5),
    TOT_REC NUMBER,
    TOT_SUCC NUMBER);
    CREATE TABLE COMM
    (SRC_FILE_ID VARCHAR2(14),
    REC_ID NUMBER,
    STATUS CHAR(1));
    INSERT INTO FILE_STATUS VALUES ('12345678', 'CM_LIBM.TXT', 'LIBM', 5, 4);
    INSERT INTO FILE_STATUS VALUES ('12345679', 'CM_HIPNT.TXT', 'HIPNT', 4, 0);
    INSERT INTO COMM VALUES ('12345678', 1, 'T');
    INSERT INTO COMM VALUES ('12345678', 3, 'T');
    INSERT INTO COMM VALUES ('12345678', 4, 'P');
    INSERT INTO COMM VALUES ('12345678', 5, 'P');
    COMMIT;Here is the query that I wrote to give me the details of the file that has been loaded into the system. It reads the file status and commission table to show file name, total records loaded, total records successfully loaded to the commission table and number of records that has been finally transmitted (status=T) to other systems.
    SELECT
        FS.CARR_CD
        ,FS.FILE_NAME
        ,FS.FILE_ID
        ,FS.TOT_REC
        ,FS.TOT_SUCC
        ,NVL(C.TOT_TRANS, 0) TOT_TRANS
    FROM FILE_STATUS FS
    LEFT JOIN
        SELECT SRC_FILE_ID, COUNT(*) TOT_TRANS
        FROM COMM
        WHERE STATUS = 'T'
        GROUP BY SRC_FILE_ID
    ) C ON C.SRC_FILE_ID = FS.FILE_ID
    WHERE FILE_ID = '12345678';In production this query has more joins and is taking lot of time to process.. the main culprit for me is the join on COMM table to get the count of number of transactions transmitted. Please can you give me tips to optimize this query to get results faster? Do I need to remove group and use partition or something else. Please help!

    I get 2 rows if I use my query with your new criteria. Did you commit the record if you are using a second connection to query? Did you remove the criteria for file_id?
    select carr_cd, file_name, file_id, tot_rec, tot_succ, tot_trans
      from (select fs.carr_cd,
                   fs.file_name,
                   fs.file_id,
                   fs.tot_rec,
                   fs.tot_succ,
                   count(case
                            when c.status = 'T' then
                             1
                            else
                             null
                          end) over(partition by c.src_file_id) tot_trans,
                   row_number() over(partition by c.src_file_id order by null) rn
              from file_status fs
              left join comm c
                on c.src_file_id = fs.file_id
             where carr_cd = 'LIBM')
    where rn = 1;
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS
    LIBM    CM_LIBM.TXT          12345678                5          4          2
    LIBM    CM_LIBM.TXT          12345677               10          0          0Using RANK can potentially produce multiple rows to be returned though your data may prevent this. ROW_NUMBER will always prevent duplicates. The ordering of the analytical function is irrelevant in your query if you use ROW_NUMBER. You can remove the outermost query and inspect the data returned by the inner query;
    select fs.carr_cd,
           fs.file_name,
           fs.file_id,
           fs.tot_rec,
           fs.tot_succ,
           count(case
                    when c.status = 'T' then
                     1
                    else
                     null
                  end) over(partition by c.src_file_id) tot_trans,
           row_number() over(partition by c.src_file_id order by null) rn
    from file_status fs
    left join comm c
    on c.src_file_id = fs.file_id
    where carr_cd = 'LIBM';
    CARR_CD FILE_NAME            FILE_ID           TOT_REC   TOT_SUCC  TOT_TRANS         RN
    LIBM    CM_LIBM.TXT          12345678                5          4          2          1
    LIBM    CM_LIBM.TXT          12345678                5          4          2          2
    LIBM    CM_LIBM.TXT          12345678                5          4          2          3
    LIBM    CM_LIBM.TXT          12345678                5          4          2          4
    LIBM    CM_LIBM.TXT          12345677               10          0          0          1

  • How to update a People and group field using a sandbox solution

    Hi,
    I am creating a sandbox solution for office 365 and creating a custom form using visual web part, which will allow users to enter data in a custom list.
    And that list also have a user field. I am able to get SharePoint user field on the form (using javascript) which is searching for the user and get a value (working fine).
    Issue: But I am not able to save the user value. Because to save user value I require web, UserID and login name, to construct SPFieldUserValue object or string in "111;#TestUser" format. Moreover that user should be present in
    SiteUserInfoList. 
    I tried web.EnsureUser() but did not work under sanbox solution.
    Can you please provide any pointer or workaround to the problem? I may be missing something here.
    Thanks,
    Himanshu

    Hi,
    According to your description, my understanding is that you want to update the people and group field in Sandbox solution.
    In the sandbox solution, you can still use the web.EnsureUser() function to get the user information, see the thread below:
    EnsureUser in sandboxed solution
    In additional, there is a demo with your similiar requirement for your reference:
    Using the People Picker Control in Sandbox Solutions / Office 365
    Thanks
    Best Regards,
    Jerry Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

  • HT4623 I downloaded update with itunes and now all I see is itunes logo and arrow to a plug

    I downloaded an update with itunes and now myiphone is black and only shows itunes logo with an arrow and plug.  no phone tried holding down on off still black  please help I need this phone

    http://support.apple.com/kb/ht1808

  • Hard currency is not valuated in FAGL_FC_VAL along with local and group currency

    Hi All,
    I have the below system settings for FOREX revaluation. The revaluation is not happening for Hard currency along with local and group currency. The test data and other settings seams to be fine as the below mentioned workaround works perfectly for hard currency revaluation.
    I would like to take your expert feedback on this issue to confirm whether this is how SAP works or its an issue with FAGL_FC_VAL program.
    System Settings:
    Currencies in company code
    local currency      group currency      hard currency
    10                             30                         40
    USD                          USD                    UYU
    FOREX settings:
    Work around found:
    Define two Valuation area, say
    1. Valuation Area: A1 which will have currency type 10 and 30.
    2. Valuation Area: A2 which will have only the currency type 40.
    3. Run FAGL_FC_VAL twice for these area.
    Issue with this work around:
    1. The valuation area is assigned to one accounting principle (which is in turn assigned to a specific ledger).
    2. Thus, if I have different accounting FOREX process to be followed in different ledgers (say IFRS ledger, Local Ledger, Tax ledger) then I need to create 2 valuation area (as per above workaround) for each ledgers and run FAGL_FC_VAL for each of these valuation areas.
    Thanks & Regards
    Nikhil Kothari

    Hi Experts,
    Any views on the above issue?
    Thanks & Regards
    Nikhil Kothari

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • Logs are generating with owner and group as 'root'

    Hi,
    In our newly installed and configured Oracle application server(10.1.3.5), the logs are generating with owner and group as 'root'.
    Location: $ORACLE_HOME/Apache/Apache/logs
    -rw-r----- 1 root root 6700 Apr 3 02:03 access_log.1364947200
    -rw-r----- 1 root root 430 Apr 3 02:04 error_log.1364947200
    We have configured it on port 80. For this the '.apachectl' ownership and permissions are changed as below:
    -rwsr-s--- 1 root dba 1703780 Jul 21 2009 .apachectl
    Kindly let me know what are the changes to be made, for the logs to be generated with the group as 'dba' instead of 'root'.
    Thanks.
    Edited by: 985284 on Apr 3, 2013 3:14 AM
    Edited by: 985284 on Apr 3, 2013 4:22 AM

    Ok - that is quit weird then. If you want to run the HTTP Server on a privileged port, you basically change the ownership of the .apachectl executable :
    cd ORACLE_HOME/Apache/Apache/bin
    chown root .apachectl
    chmod 6750 .apachectlas per [url http://docs.oracle.com/cd/B25221_05/core.1013/b25209/ports.htm#CIHJEEJH]documentation.
    Your user and group directive should be set to :
    User oracle
    Group dbaUpon starting, the http server would start as root and then switch the effective userid of the process from root to oracle. In the process list (ps -ef | grep httpd), you should see oracle.
    Do you have the same configuration and what do you see in the process list?

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

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

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

  • TS3694 my iphone 4s said it needed updating to ios7.2 and so far its displaying the itunes logo and saying plug into itunes so i tried updating with itunes and it keeps saying it has failed (3194)

    my iphone 4s said it needed updating to ios7.2 and so far its displaying the itunes logo and saying plug into itunes so i tried updating with itunes and it keeps saying it has failed (3194)

    Hello Amz_Bajwa,
    Thanks for using Apple Support Communities.
    For more information on this, take a look at:
    iTunes: Specific update-and-restore error messages and advanced troubleshooting
    http://support.apple.com/kb/TS3694#error3194
    Unable to contact the iOS software update server gs.apple.com
    Error 1004, 1013, 1638, 3014, 3194: These errors may be the result of the connection to gs.apple.com being redirected or blocked. Follow these steps to resolve these errors:
    Install the latest version of iTunes.
    Check security software and ensure that communication to gs.apple.com is allowed. Follow these stepsfor assistance with security software.
    Check the hosts file. The restore will fail if there is an active entry to redirect gs.apple.com. Follow theadvanced iTunes Store troubleshooting steps to edit the hosts file or revert to a default hosts file. See "Blocked by configuration: (Mac OS X/Windows) > Rebuild network information."
    Try to restore from another known-good computer and network.
    If the errors persist on another computer, the device may need service.
    Best of luck,
    Mario

  • Help with exercise on joins and group by

    Could someone help me with an exercise I'm working on? This isn't "homework", per se, as it's not an assignment, I'm just doing my own personal research.
    I have the usual tables "DEPARTMENT" and "EMPLOYEE", with the following columns:
    Department:
    * NAME
    * ID
    Employee:
    * SSN
    * NAME
    * DEPT_ID
    * SALARY
    I'm able to build a query that summarizes the departments with total employee salary > 30000, like this:
    select dept_id, sum(salary) from employee group by dept_id having sum(salary) > 30000;
    What I'd like to extend this to is a summary of departments with total employee salary > 30000 OR no employees at all (or total salary = 0, conceptually).
    I imagine this will include a left outer join, but I can't get this to work.

    http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/aggreg.htm#sthref1670
    http://www.oracle.com/technology/products/oracle9i/daily/oct10.html
    http://www.dba-oracle.com/t_sql99_with_clause.htm
    http://www.psoug.org/reference/with.html
    WITH clause is used for reusability of sub queries within a query. And in this case it is useful to build the query without having to create a table with data and show the results.
    SQL> select 1 dept_id, 'ABC' dept_name from dual;
       DEPT_ID DEP
             1 ABCHere I am selecting some static values from dual table where I say I want 1 as dept_id and its name as ABC.
    SQL> select 1 dept_id, 'ABC' dept_name from dual union all
      2      select 2 dept_id, 'XYZ' dept_name from dual union all
      3      select 3 dept_id, 'MNO' dept_name from dual;
       DEPT_ID DEP
             1 ABC
             2 XYZ
             3 MNOIn the above query I am selecting 3 static department ids and names in three separate queries and combining them using union all. Thus I am getting them as three rows.
    SQL> with dept as(
      2      select 1 dept_id, 'ABC' dept_name from dual union all
      3      select 2 dept_id, 'XYZ' dept_name from dual union all
      4      select 3 dept_id, 'MNO' dept_name from dual )
      5  --
      6  select * from dept;
       DEPT_ID DEP
             1 ABC
             2 XYZ
             3 MNOHere, In the above query, I just named the previous query as "dept" and I am just selecting all from "dept". You can say it something like a virtual table which has data based on a query, that can be reused in other/main query. The limitations, uses and elaborate descriptions are available in the links I provided.

  • Rewrite the query with out joins and group by

    Hi,
    This was an interview question.
    Table Names: bookshelf_checkout
    bookshelf
    And the join condition between these two tables is title
    We need to rewrite below query without using join condition and group by clause ?
    SELECT b.title,max(bc.returned_date - bc.checkout_date) "Most Days Out"
               FROM bookshelf_checkout bc,bookshelf b
               WHERE bc.title(+)=b.title
               GROUP BY b.title;When I was in college, I read that most of the SELECT statements can be replaced by basic SQL operations (SET OPERATORS). Now I am trying to rewrite the query with SET operators but not able to get the exact result.
    Kindly help me on this.
    Thanks,
    Suri

    Something like this?
      1  WITH books AS (
      2  SELECT 'title 1' title FROM dual UNION ALL
      3  SELECT 'title 2' FROM dual UNION ALL
      4  SELECT 'title 3' FROM dual ),
      5  bookshelf AS (
      6  SELECT 'title 1' title, DATE '2012-05-01' checkout_date, DATE '2012-05-15' returned_date FROM dual UNION ALL
      7  SELECT 'title 1' title, DATE '2012-05-16' checkout_date, DATE '2012-05-20' returned_date FROM dual UNION ALL
      8  SELECT 'title 2' title, DATE '2012-04-01' checkout_date, DATE '2012-05-15' returned_date FROM dual )
      9  SELECT bs.title, MAX(bs.returned_date - bs.checkout_date) OVER (PARTITION BY title) FROM bookshelf bs
    10  UNION
    11  (SELECT b.title, NULL FROM books b
    12  MINUS
    13* SELECT bs.title, NULL FROM bookshelf bs)
    SQL> /
    TITLE   MAX(BS.RETURNED_DATE-BS.CHECKOUT_DATE)OVER(PARTITIONBYTITLE)
    title 1                                                           14
    title 2                                                           44
    title 3Lukasz

  • Materialized View  with Joins and Possibilities of Partitioning

    Hi,
    We have a materialized view which has a data to query around 12 gb. The query goes some thing like
    this.
      Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
      from a,b,c
      where a.c1=b.c1
      --and the where condition goes on...
      --i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
       Now i have few questions here.
    Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
    Question No 1
    Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
    Question No 2
    Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
    Question No 3
    How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
    Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
    Thanks in anticipation for a good round of discussion

    Hi,
    We have a materialized view which has a data to query around 12 gb. The query goes some thing like
    this.
      Select a.c1,a.c2,b.c1,b.c2,c.c1,c.c2
      from a,b,c
      where a.c1=b.c1
      --and the where condition goes on...
      --i.e Basically joining 3 different tables with complex join conditions but without any group functions and subqueries.
       Now i have few questions here.
    Firstly as the Mview is created with joins we will have to create separate logs for each tables and we have did the same. The logs are created with rowid and sequence for better performance during refresh.
    Question No 1
    Is this is a best approach for materializing a query with complex join conditions. Or Is it better to make 3 different materialized views for each 3 tables and join those 3 MViews and write a query for my report. I ask this question just to make sure the refresh time is brought down by this method. But as such as we have created 3 different logs for 3 tables the refresh must be happening separately.
    Question No 2
    Data is likely to grow faster and faster on this. So we have a idea of making this a partitioned Mview. Can the Pro's advice me on this and suggest me the right practice for the same and help me to correct links from where i can pick a example and continue from there.
    Question No 3
    How to find whether the materialized view has refreshed on a fast mode or complete mode after the last refresh.
    Apart from querying and checking the rowid which i feel is quiet cumbersome for a mview with a data volume like what we have. By default when i see the info in TOAD for this Mview it shows Refresh Mode as "Force". But how to ascertain this.
    Thanks in anticipation for a good round of discussion

  • EA1 - SQL Formatter issues (JOINs and GROUPs and ORDER BY oh my ;)

    Great job with improving the SQL Formatter, but it still has some bugs that need to be worked out.
    The key words JOIN and it's modifiers INNER, LEFT, RIGHT and FULL OUTER are not recognized as master key words. As such they end up flush against the left margin Also when GROUP BY and/or ORDER BY key words are present in an outer most select statement the other key words are not indented far enough to be right aligned with the end of the word BY and are indented too far to be right aligned with the word GROUP or ORDER. In sub queries, GROUP and ORDER BY are correctly right aligned with their respective SELECT statements.

    We're picking up and collating the Formatter issues. I'll add these.
    Specific bug for these #7013462
    Sue

  • Oracle Syntax for Update with Join

    Can anyone help with the Oracle Syntax on and update that includes a join?
    This is what I've got:
    Update
    (SELECT a.DOCUMENT_NO
    From DOCUMENT_CONTROL a, DOCNOTEST b
    where a.DOCUMENT_NO = b.DOCUMENT_NO)
    set a.PATH = NULL
    Everything I try leads to another error message. With the current code I'm getting the error message: ORA-00971 a.path invalid identifier.
    I am much more familiar with SQL Server (if you can't tell :) This is the way I would write the above in SQL Server.
    UPDATE DOCUMENT_CONTROL
    Set [Path] = ''
    FROM DOCUMENT_CONTROL
    INNER JOIN DOCNOTEST
    ON DOCUMENT_CONTROL.DOCUMENT_NO=DOCNOTEST.DOCUMENT_NO
    where DOCUMENT_CONTROL.DOCUMENT_NO=DOCNOTEST.DOCUMENT_NO
    Does anyone have any advice for me? Thanks in advance

    Alternate syntax since it seems you're not able to update the join...
    update DOCUMENT_CONTROL a
    set
       a.path = null
    where a.path is not null
    and exists
       select null
       from DOCNOTEST b
       where  a.DOCUMENT_NO = b.DOCUMENT_NO
    );

  • Update with exists and subquery

    Hi how to pass index to this sql
    Table pap ( eqid,seq,histseq,docno,status,value1,value2)
    PK(eqid,seq,histseq) and indx (docno)
    table pa ( eqid,seq,docno,status,value1,value2)
    PK(eqid,seq) and indx (docno)
    update pa
    set (value1,value2) = (select pap.value1,pap.value2 from pap
    where pap.eqid = pa.eqid
    and pap.seq = pa.seq
    and pap.histseq =1
    and pap.docno <> pa.docno
    and pap.status = 4 )
    where pa.status=1
    and exists ( select 1 from pap
    where pap.eqid = pa.eqid
    and pap.seq = pa.seq
    and pap.histseq =1
    and pap.docno <> pa.docno
    and pap.status =4 )
    It is doing fulltable scan on pa and using hash join .
    How to write update with subquery method also ?

    There's nothing wrong with a full scan.
    Please read this explanation/example: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9422487749968
    If you want more explanation then please follow these guidelines below, so we have sufficient inputs:
    [When your query takes too long...|http://forums.oracle.com/forums/thread.jspa?messageID=1812597#1812597]
    [How to post a SQL statement tuning request|http://forums.oracle.com/forums/thread.jspa?threadID=863295&tstart=0]
    Remember to put the tag befor and after the examples you post.
    See http://forums.oracle.com/forums/help.jspa regarding tags.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • I can no longer sync my iphone 4 calendar with my Mac

    I have a Mac desktop snow leopard version 10.6.8, and an iphone 4.  I can no longer sync my iphone  calendar with ical on my Mac.  I does sync from ical to the iphone however  Help. Thanks,

  • SRM PO created with wrong company code

    Hello,         The users have created several PO in SRM with wrong company code. The user was found in the wrong organization structure during the creation of shopping and approval. The PO did not get transfer to the Back because of this. Is there a

  • How do I install cloud apps to a non OS drive

    I went to preferences and put in E:\Program Files\Adobe and my programs are still installing to the C:\ drive  These apps are going to run my SSD OS drive out of space.  This so called "simple" installation where the manager does the installation for

  • Insert flash video? Won't play

    Any tips on inserting Flash video into a project in Captivate 4? I can get video to appear an play in Preview, but after publishing, the video doesn't appear and the slide forwards. (Also, there seems to be a conssitent problme where preview is inacc

  • No image sin my podcast

    Hi, I have images on my podcast track and in my episode cover. I am able to Send podcast to iTunes with no problem, but when I play from iTunes there are no images. Well there one for the cover but its not even one I've used in the podcast. Any idea