Rewrite sql query

Hello,
I need to rewrite this SQL query to give the same result, but in more resorcefull manner.
Probably using aggregation, but I am not sure.
Can somebody give me a head start.
desc resource_bundles
Name          Null     Type               
LOCALE        NOT NULL CHAR(5)            
BUNDLE_NAME   NOT NULL VARCHAR2(32)       
RESOURCE_NAME NOT NULL VARCHAR2(64)       
VALUE_STRING           VARCHAR2(2048 CHAR)
select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string
                                         from resource_bundles b
                                         where b.bundle_name = a.bundle_name
                                         and b.resource_name = a.resource_name
                                         and b.locale = 'en_US'
                                        )as English,
                                         (select c.value_string
                                         from resource_bundles c
                                         where c.bundle_name = a.bundle_name
                                         and c.resource_name = a.resource_name
                                         and c.locale = 'ru_RU'
                                         ) as Russian,
                                         (select d.value_string
                                         from resource_bundles d
                                         where d.bundle_name = a.bundle_name
                                         and d.resource_name = a.resource_name
                                         and d.locale = 'it_IT'
                                        ) as Italian
from resource_bundles a
where a.locale = 'cs_CZ';Thank you
Edited by: BluShadow on 15-Apr-2011 12:20
added {noformat}{noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

It is always helpful to provide the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
Also see the third post in this thread:
{thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Rewrite SQL query to improve performance

    Hello,
    The below queries are very time consuming.Could you please suggest how to improve performance for these 2 queries:
    QUERY1:
    SELECT avbeln aposnr aauart avkorg avtweg aspart
    avkbur akunnr bmatnr bkwmeng b~vrkme
    bnetwr bwerks blgort bvstel babgru berdat b~ernam
    cfaksk cktext cvdatu czzbrsch ckvgr1 caugru
    INTO CORRESPONDING FIELDS OF TABLE g_t_sodata
                FROM vapma AS a INNER JOIN vbap AS b ON
                avbeln = bvbeln AND aposnr = bposnr
                INNER JOIN vbak AS c ON avbeln = cvbeln
                  WHERE a~vkorg IN so_vkorg
                  AND a~vtweg IN so_vtweg
                  AND a~vkbur IN so_vkbur
                  AND a~auart IN so_auart
                  AND a~vbeln IN so_vbeln
                  AND b~abgru IN so_abgru
                  AND c~faksk IN so_faksk
                  AND ( b~erdat GT g_f_zenkai_date OR
            ( berdat EQ g_f_zenkai_date AND berzet GE g_f_zenkai_time ) )
            AND ( b~erdat LT g_f_kaisi_date  OR
             ( berdat EQ g_f_kaisi_date  AND berzet LT g_f_kaisi_time ) ).
    QUERY2:
    SELECT avbeln aposnr aauart avkorg avtweg aspart
            avkbur akunnr bmatnr bkwmeng  b~vrkme
            b~netwr
            bwerks blgort bvstel babgru berdat bernam
            cfaksk cktext cvdatu czzbrsch ckvgr1 caugru
            INTO CORRESPONDING FIELDS OF TABLE g_t_sodata
           FROM vapma AS a INNER JOIN vbap AS b ON
           avbeln = bvbeln AND aposnr = bposnr
           INNER JOIN vbak AS c ON avbeln = cvbeln
             WHERE a~vkorg IN so_vkorg
             AND a~vtweg IN so_vtweg
             AND a~vkbur IN so_vkbur
             AND a~auart IN so_auart
             AND a~vbeln IN so_vbeln
             AND b~abgru IN so_abgru
             AND c~faksk IN so_faksk.

    Questions like this a one of the favorites here in this forum.
    I guess that the statements are o.k.
    The problem is the usage!  There are so many Ranges, if they are filled then some index should support it. If no range is filled then it is usually slow, you can not do anything.
    You must find out, which are actually used and under which conditions it is slow and when it is o.k.
    Ask again, when you can provide the actual cases.
    Use SQL trace to check the performance:
    SQL trace:
    The SQL Trace (ST05) – Quick and Easy
    I know the probabilty is high, that you will ignore this recommendation and you will points to the
    'Use FOR ALL ENTRIES' recommendations' ... but then I can not help you.
    Siegfried

  • Parsing and rewriting an SQL query

    Hi all,
    I need to rewrite bits of a valid PL/SQL query. In order to do so, I need semantic information about the query, such as "what are the table names columns are being selected from" or "do aggregate functions in a select provide column alias in order to use the query in +CREATE TABLE AS+ ...".
    Is it possible to somehow "ask" the Oracle parser for those bits of semantic info? I am using 9i.
    E.g.
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE))
    from
    TABLE_X X,
    (select NAME, VALUE from TABLE_Z where DATE_STR = '20090101') Y
    where
    will become
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE)) COL1
    from
    TABLE_X prefix. X,
    (select NAME, VALUE from prefix. TABLE_Z where DATE_STR = '20090101') Y
    where
    ...

    Thanks for your answers (which, unfortunately, do not give much hope)!
    +..so unfortunately you won't be able to use the 11g method introduced here (Anyhow still undocumented!).+
    Yes, that's very disappointing. I actually added the "has to be 9i compatible" remark after I found out the XML dump does not work on our servers - and read the manual page to realize why that's the case.
    I think you'd need to write your own, which will be extremely difficult and hard to maintain.*
    There is a BNF grammar of PL/SQL (homebrew, apparently - so no guarantees): http://www.antlr.org/grammar/1107752678378/PLSQLGrammar.g
    Now, if I only knew practical stuff about lexers and parsers and abstract syntax trees...

  • A table is 'stuck' in the Discoverer SQL query after rewriting query.

    Hi,
    I'm using Discoverer 10.1.2.2 on an Oracle 9.2.0.6.0 DB.
    I've taken an existing Work Book and modified it. I've removed several fields as well as their table from the 'Selected Items' Window. I've also removed any references to all fields in that table in all Calculations and Conditions.
    Yet when I pull the SQL from the View: SQL Inspector That table still shows up and well as the join to it and a field from that table that I'm no longer using shows up as a field in the query. I'm not sure where else to check or what else to to do get this table out of this SQL query.
    Does anyone have any suggestions?

    Hi
    This can happen when someone has drilled inside a worksheet and saved the worksheet. The original or drilled to items are remembered,sometimes long after the drill item has been dispensed with. When this happens typically the only way to remedy the situation is to rebuild the worksheet from scratch.
    Before you get into that you do need to do one final scour to make sure that there is absolutely nothing in your worksheet that could cause the folder to be used. It could be in a long forgotten calculation. Sometimes when the only way to get from one folder to another one has to go via an intermediate folder by pulling any old item and then removing the item later. The folder willstill be used though. Could this be happening here?
    If you can rule out everything from the above paragraph then I am sorry to say but it sounds like you may have to rebuild from scratch.
    Best wishes
    Michael

  • How to modify a SQL query?

    Hi all,
    I am using Crystal Reports version 10. I have a number of reports that have been written by a software vendor wherby the name of the database they were connected to when the report was written is coded into the FROM command of the reports SQL query, eg "GCUK_2" in the of the SQL snippet below.
    SELECT "Clients"."NAME", "Quotes"."QUOTE_ID", "Quote_Items"."UPRICE", "Quote_Items"."QTY", "Quote_Items"."UOM", "Quote_Items"."QUSAGE_ID", "Report_Control"."QUSAGEID", "Quote_Items"."STANDARD", "Quote_Items"."SECT_FLAG", "Quote_Items"."DISPORDER", "Quotes"."DESCRIPT", "Report_Control"."SECT_NAME", "Quote_Items"."CNT", "Category_and_Type"."TYPEDESC", "Quote_Items"."DESCRIPT", "Report_Control"."DISP_SORT"
    FROM   ((("GCUK_2"."schedwin"."QTE_CTRL" "Report_Control" INNER JOIN "GCUK_2"."schedwin"."QUSAGE" "Quote_Items" ON "Report_Control"."QUSAGEID"="Quote_Items"."QUSAGE_ID") LEFT OUTER JOIN "GCUK_2"."schedwin"."QUOTES" "Quotes" ON
    I have tried setting the Datasource Location, but it doesn't change the query at all. I have read on another forum that you can generate another SQL query using the Database Expert, Current Connections, then right click the Add Command for the database you want to create a SQL command. Is this the only way to update the database names in the query?
    Thanks,
    Scott.

    Hi Sourashree,
    Thanks for that. All the reports were created by the vendor using tables as opposed to the command object. I would have thought that changing the datasource would automatically cause Crystal to rewrite the SQL query syntax, but this doesn't appear to be the case.
    Yes, I've noticed that modifying the record selection will change the sql query. The only way I can see to change the database name in the query is to change to the desired databsource and then remove and re-insert the tables, which will then update the query with the correct name. However, this seems to be a convoluted way of changing the db name in the query.

  • SQL Query produces different results when inserting into a table

    I have an SQL query which produces different results when run as a simple query to when it is run as an INSERT INTO table SELECT ...
    The query is:
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      The INSERT INTO code:
    TRUNCATE TABLE applicant_summary;
    INSERT /*+ APPEND */
    INTO     applicant_summary
    (  account_number
    ,  main_borrower_status
    ,  num_apps
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      When run as a query, this code consistently returns 2 for the num_apps field (for a certain group of accounts), but when run as an INSERT INTO command, the num_apps field is logged as 1. I have secured the tables used within the query to ensure that nothing is changing the data in the underlying tables.
    If I run the query as a cursor for loop with an insert into the applicant_summary table within the loop, I get the same results in the table as I get when I run as a stand alone query.
    I would appreciate any suggestions for what could be causing this odd behaviour.
    Cheers,
    Steve
    Oracle database details:
    Oracle Database 10g Release 10.2.0.2.0 - Production
    PL/SQL Release 10.2.0.2.0 - Production
    CORE 10.2.0.2.0 Production
    TNS for 32-bit Windows: Version 10.2.0.2.0 - Production
    NLSRTL Version 10.2.0.2.0 - Production
    Edited by: stevensutcliffe on Oct 10, 2008 5:26 AM
    Edited by: stevensutcliffe on Oct 10, 2008 5:27 AM

    stevensutcliffe wrote:
    Yes, using COUNT(*) gives the same result as COUNT(1).
    I have found another example of this kind of behaviour:
    Running the following INSERT statements produce different values for the total_amount_invested and num_records fields. It appears that adding the additional aggregation (MAX(amount_invested)) is causing problems with the other aggregated values.
    Again, I have ensured that the source data and destination tables are not being accessed / changed by any other processes or users. Is this potentially a bug in Oracle?Just as a side note, these are not INSERT statements but CTAS statements.
    The only non-bug explanation for this behaviour would be a potential query rewrite happening only under particular circumstances (but not always) in the lower integrity modes "trusted" or "stale_tolerated". So if you're not aware of any corresponding materialized views, your QUERY_REWRITE_INTEGRITY parameter is set to the default of "enforced" and your explain plan doesn't show any "MAT_VIEW REWRITE ACCESS" lines, I would consider this as a bug.
    Since you're running on 10.2.0.2 it's not unlikely that you hit one of the various "wrong result" bugs that exist(ed) in Oracle. I'm aware of a particular one I've hit in 10.2.0.2 when performing a parallel NESTED LOOP ANTI operation which returned wrong results, but only in parallel execution. Serial execution was showing the correct results.
    If you're performing parallel ddl/dml/query operations, try to do the same in serial execution to check if it is related to the parallel feature.
    You could also test if omitting the "APPEND" hint changes anything but still these are just workarounds for a buggy behaviour.
    I suggest to consider installing the latest patch set 10.2.0.4 but this requires thorough testing because there were (more or less) subtle changes/bugs introduced with [10.2.0.3|http://oracle-randolf.blogspot.com/2008/02/nasty-bug-introduced-with-patch-set.html] and [10.2.0.4|http://oracle-randolf.blogspot.com/2008/04/overview-of-new-and-changed-features-in.html].
    You could also open a SR with Oracle and clarify if there is already a one-off patch available for your 10.2.0.2 platform release. If not it's quite unlikely that you are going to get a backport for 10.2.0.2.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Problem using alias field names in a sql query

    Hello,
    I have a question regarding a simple Oracle database SQL query writeup:
    In the following (badly written but properly working) SQL query:
    Query 1:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    (soe.field5 - (soe.field2 + soe.field3)) as field6,
    (select comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 1:
    I am re writing the code (soe.field2 + soe.field3) to get the alias field4 or column name field4 that I have created on the fly in the previously for use with the following fields. Can't I rewrite the query as follows. There is something simple missing!
    Query 2:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6, <<< field4 does not work here
    (select
    comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select
    soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 2:
    Similar to the above problem, I was thinking to get a field parValue out of the CompTable table and re-use many times rather than the code shown in Query 1:
    Query 3:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6,
    soe.field7* (select comp.parValue from CompTable comp) as parValue1,
    soe.field8 - (parValue1*soe.field7+ soe.field9) as field10      <<<< parvalue1 does not work here
    parValue1*soe.field9 as TaxCondition               <<<< parvalue1 does not work here
    from
    SomeTable soe
    See that the query becomes so simple, but the above query does not work. There is something fundamentally wrong in my usage of the alias field names in creating other fields. The Query1 seems to be the only working option but its very slow as I am redoing and re-writing the whole code again and again to get the parValue field out of the CompTable table for use to create many other fields.
    I will appreciate if you can guide me in the right direction on this issue.
    Thanks and Regards
    Rama

    SELECT tmp.contract_no, tmp.Actual, tmp.Actual - tmp.NbHours
    FROM ( SELECT t.contract_no, sum(l.hrs) AS Actual, (c.labour_hours * c.labour_progress_per) / 100 AS NbHours
    FROM TASK_DELEGATION t
    INNER JOIN COST_CODE c
    ON t.cost_code = c.cost_code AND t.contract_no = c.contract_no AND t.is_inactive=0
    INNER JOIN Labour.dbo.LABOURALLOT l
    ON l.contractNo = c.contract_no AND l.costcode = c.cost_code AND l.pm = 'N'
    GROUP BY t.contract_no, c.labour_hours, c.labour_progress_per
    ) tmp

  • Help in rewrite the Query

    Hello
    I have one query taking time to fetch the records. Table contains just 40,000 thousands records but lots of case statement in the query, I just remove lots of case statement there are lot more...
    Can you please help me out to rewrite the query to fetch the records faster. Also Right now there are no indexes on the table....
    SELECT O.cn,
           O.BEN_LAST_NAME,
           O.BEN_FIRST_NAME,
           O.BEN_MI,
           O.SSN,
           O.DOB,
           O.SEX,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 00 AND 34 THEN
               1
              ELSE
               0
           END AS AGE_GROUP0_34_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 35 AND 44 THEN
               1
              ELSE
               0
           END AS AGE_GROUP35_44_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 45 AND 54 THEN
               1
              ELSE
               0
           END AS AGE_GROUP45_54_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 55 AND 59 THEN
               1
              ELSE
               0
           END AS AGE_GROUP55_59_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 60 AND 64 THEN
               1
              ELSE
               0
           END AS AGE_GROUP60_64_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 65 AND 69 THEN
               1
              ELSE
               0
           END AS AGE_GROUP65_69_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 70 AND 74 THEN
               1
              ELSE
               0
           END AS AGE_GROUP70_74_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 75 AND 79 THEN
               1
              ELSE
               0
           END AS AGE_GROUP75_79_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 80 AND 84 THEN
               1
              ELSE
               0
           END AS AGE_GROUP80_84_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 85 AND 89 THEN
               1
              ELSE
               0
           END AS AGE_GROUP85_89_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 90 AND 94 THEN
               1
              ELSE
               0
           END AS AGE_GROUP90_94_F,
           CASE
              WHEN O.SEX = 'F' AND O.AGE BETWEEN 95 AND 00 THEN
               1
              ELSE
               0
           END AS AGE_GROUP95_GT_F,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 00 AND 34 THEN
               1
              ELSE
               0
           END AS AGE_GROUP0_34_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 35 AND 44 THEN
               1
              ELSE
               0
           END AS AGE_GROUP35_44_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 45 AND 54 THEN
               1
              ELSE
               0
           END AS AGE_GROUP45_54_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 45 AND 59 THEN
               1
              ELSE
               0
           END AS AGE_GROUP55_59_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 60 AND 64 THEN
               1
              ELSE
               0
           END AS AGE_GROUP60_64_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 65 AND 69 THEN
               1
              ELSE
               0
           END AS AGE_GROUP65_69_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 70 AND 74 THEN
               1
              ELSE
               0
           END AS AGE_GROUP70_74_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 75 AND 79 THEN
               1
              ELSE
               0
           END AS AGE_GROUP75_79_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 80 AND 84 THEN
               1
              ELSE
               0
           END AS AGE_GROUP80_84_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 85 AND 89 THEN
               1
              ELSE
               0
           END AS AGE_GROUP85_89_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 90 AND 94 THEN
               1
              ELSE
               0
           END AS AGE_GROUP90_94_M,
           CASE
              WHEN O.SEX = 'M' AND O.AGE BETWEEN 95 AND 00 THEN
               1
              ELSE
               0
           END AS AGE_GROUP95_GT_M,
           O.YEAR,
          CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                            ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                            AND m2.YEAR = hm.YEAR
                            AND o.cn = m2.cn
                            AND o.YEAR = hm.YEAR
                            AND m1.hcc_model_category1 = 1
                            AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS DISEASE_COEF_HCC1,
          CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                            ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                            AND m2.YEAR = hm.YEAR
                            AND o.cn = m2.cn
                            AND o.YEAR = hm.YEAR
                            AND m1.hcc_model_category1 = 2
                            AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS DISEASE_COEF_HCC2,
           CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                            ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                            AND m2.YEAR = hm.YEAR
                            AND o.cn = m2.cn
                            AND o.YEAR = hm.YEAR
                            AND m1.hcc_model_category1 = 5
                             AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS       DISEASE_COEF_HCC5,
            CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                            ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                            AND m2.YEAR = hm.YEAR
                            AND o.cn = m2.cn
                            AND o.YEAR = hm.YEAR
                            AND m1.hcc_model_category1 = 7
                            AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS      DISEASE_COEF_HCC7,
           CASE WHEN EXISTS (SELECT m1.hcc_model_category1 FROM HCC_MODEL_DIAGNOSIS M1 , HCC_MODEL_DIAGNOSIS_MAPPING HM
                            ,mor222 m2 WHERE m1.map_id = hm.map_id_ref
                            AND m2.YEAR = hm.YEAR
                            AND o.cn = m2.cn
                            AND o.YEAR = hm.YEAR
                            AND m1.hcc_model_category1 = 8
                            AND m2.diag_code = m1.icd9cmscode) THEN 1 ELSE 0 END AS       DISEASE_COEF_HCC8                   
      FROM (SELECT T.cn,
                   T.BEN_LAST_NAME,
                   T.BEN_FIRST_NAME,
                   T.BEN_MI,
                   T.SSN,
                   TO_DATE(T.DOB, 'YYYYMMDD') AS DOB,
                   T.SEX,
                   TRUNC(MONTHS_BETWEEN(TO_DATE('01/01/' || T.YEAR, 'MM/DD/YYYY'),
                                        TO_DATE(T.DOB, 'YYYYMMDD')) / 12) AS AGE,
                   T.YEAR
              FROM mor111 T ) O Thanks in advance!
    Kind regards,
    Nik

    Ok, so I am going to be a little bit kinder then your first reply, but not much.
    From what can tell you are doing medical management and are trying to select by AGE/GENDER CELLS and this is common when trying to deal with RBRVS.
    This is by far some of the worst sql I have ever seen, sorry but it just is.
    So please report this either as a new post or as a reply and:
    1. At least post the table definitions and if you can some sample data.
    2. Get rid of almost all the case selectors.
    3. Describe the output you need.
    As it is this is unreadable.
    After that we can talk more.
    Edited by: FlyingGuy on Oct 11, 2011 5:13 PM

  • SQL Query taking long time....its very urgent !!!

    Hi All,
    Can any body help me out to tune this query... its cost is 62,900.. and thete is full table scan on ap_invoices_all...
    For one invoice ID its taking 20 sccs...
    SELECT /*+ INDEX  ( i2 AP_INVOICES_N8 )  INDEX  ( i1 AP_INVOICES_N8 )   */ DISTINCT ou.name operating_unit,
    NVL(SUBSTR(UPPER(TRANSLATE(i1.invoice_num,'a!@#\/-_$%^&*.','a')),
    1,:P_MATCH_LENGTH),'NomatchKluDge1') match_string,
    UPPER(v.vendor_name) upper_supplier_name,
    i1.invoice_num invoice_number,
    to_char(i1.invoice_date,'DD-MON-YYYY') invoice_date,
    --i1.invoice_date invoice_date,
    NVL(i1.invoice_amount,0) invoice_amount,
    i1.invoice_currency_code currency_code,
    v.segment1 supplier_number,
    v.vendor_name supplier_name,
    ssa.vendor_site_code supplier_code,
    lc.displayed_field invoice_type,
    poh.segment1 po_number,
    (select min(por.release_num)
    from po_releases_all por
    where poh.po_header_id = por.po_header_id) release_num,
    gcc.segment1 location,
    i1.payment_method_code payment_method_code,
    DECODE(LENGTH(TO_CHAR(aca.check_number)),9,aca.check_number,aca.doc_sequence_value) payment_doc_number
    FROM ap_invoices_all i1,
    ap_invoices_all i2,
    ap_suppliers v ,
    ap_supplier_sites_all ssa,
    ap_lookup_codes lc,
    /* (select distinct pha.SEGMENT1, i.PO_HEADER_ID, i.INVOICE_ID
    from ap_invoice_lines_all i
    ,po_headers_all pha
    where pha.PO_HEADER_ID = i.PO_HEADER_ID) poh, */
    po_headers_all poh,
    ap_invoice_lines_all ail,
    ap_invoice_distributions_all aida,
    gl_code_combinations gcc,
    ap_checks_all aca,
    ap_invoice_payments_all ipa,
    hr_all_organization_units ou
    WHERE i1.invoice_id <> i2.invoice_id
    AND NVL(substr(upper(translate(i1.invoice_num,'a!@#\/-_$%^&*.','a')),
    1,:P_MATCH_LENGTH),'NomatchKluDge1')
    = NVL(substr(upper(translate(i2.invoice_num,'a!@#\/-_$%^&*.','a')),
    1,:P_MATCH_LENGTH),'abcdefghijklm')
    --AND i1.creation_date between :p_creation_date_from  and  :p_creation_date_to
    AND i1.cancelled_date IS NULL
    --AND i2.creation_date between  :p_creation_date_from  and  :p_creation_date_to
    AND i2.cancelled_date IS NULL
    AND i1.invoice_amount = nvl(i2.invoice_amount,-1)
    --AND i1.vendor_id      =  i2.vendor_id
    AND i1.vendor_id+0 = i2.vendor_id+0
    AND nvl(i1.vendor_id,-1) = v.vendor_id
    AND i1.invoice_id = aida.invoice_id
    AND aida.distribution_line_number = 1
    AND gcc.code_combination_id = aida.dist_code_combination_id
    AND     lc.lookup_code (+)      = i1.invoice_type_lookup_code
    AND     lc.lookup_type (+)      = 'INVOICE TYPE'
    AND i1.vendor_site_id = ssa.vendor_site_id(+)
    --AND i1.invoice_id = poh.invoice_id (+)
    AND i1.invoice_id = ail.invoice_id
    --AND ail.line_number = 1                                       
    AND aida.INVOICE_LINE_NUMBER = 1
    --AND ail.po_header_id = poh.po_header_id (+)  
    AND ail.po_header_id = poh.po_header_id
    AND ail.INVOICE_ID = aida.INVOICE_ID
    and ail.LINE_NUMBER = aida.INVOICE_LINE_NUMBER
    AND i1.invoice_id = ipa.invoice_id(+)
    AND ipa.check_id = aca.check_id(+)
    AND i1.org_id = ou.organization_id
    and i1.invoice_id = 123456
    ORDER BY upper(v.vendor_name),
    NVL(substr(upper(translate(i1.invoice_num,'a!@#\/-_$%^&*.','a')),
    1,:P_MATCH_LENGTH),'abcdefghijklm'),
    upper(i1.invoice_num);
    Regards
    --Harry                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I tried to rewrite this query to format it into something more readable. Since I can't test, this may have introduced syntax errors:
    SELECT /*+ INDEX  ( i2 AP_INVOICES_N8 )  INDEX  ( i1 AP_INVOICES_N8 )   */
           DISTINCT ou.name                             operating_unit,
           NVL(SUBSTR(UPPER(TRANSLATE(i1.invoice_num,
                            'a!@#\/-_$%^&*.','a')),
               1,:P_MATCH_LENGTH),'NomatchKluDge1')     match_string,
           UPPER(v.vendor_name)                         upper_supplier_name,
           i1.invoice_num                               invoice_number,
           to_char(i1.invoice_date,'DD-MON-YYYY')       invoice_date,
           NVL(i1.invoice_amount,0)                     invoice_amount,
           i1.invoice_currency_code                     currency_code,
           v.segment1                                   supplier_number,
           v.vendor_name                                supplier_name,
           ssa.vendor_site_code                         supplier_code,
           lc.displayed_field                           invoice_type,
           poh.segment1                                 po_number,
           (SELECT MIN(por.release_num)
            FROM   po_releases_all por
            WHERE  poh.po_header_id = por.po_header_id) release_num,
           gcc.segment1                                 location,
           i1.payment_method_code                       payment_method_code,
           DECODE(LENGTH(TO_CHAR(aca.check_number)),9,
              aca.check_number,aca.doc_sequence_value)  payment_doc_number
    FROM   ap_invoices_all i1
           INNER JOIN ap_invoices_all i2
             ON   i1.invoice_id = i2.invoice_id
             AND  i1.invoice_amount = NVL(i2.invoice_amount,-1)
             AND  i1.vendor_id+0 = i2.vendor_id+0
           INNER JOIN ap_suppliers v
             ON    NVL(i1.vendor_id,-1) = v.vendor_id
           INNER JOIN ap_lookup_codes lc,
             ON lc.lookup_code  = i1.invoice_type_lookup_code
           INNER JOIN ap_invoice_distributions_all aida
              ON    i1.invoice_id = aida.invoice_id
           INNER JOIN gl_code_combinations gcc
             ON     gcc.code_combination_id = aida.dist_code_combination_id
           INNER JOIN ap_invoice_lines_all ail
             ON     i1.invoice_id = ail.invoice_id
           INNER JOIN po_headers_all poh
             ON     ail.po_header_id = poh.po_header_id
           INNER JOIN hr_all_organization_units ou
             ON     i1.org_id = ou.organization_id
           LEFT JOIN (ap_invoice_payments_all ipa
                       INNER JOIN ap_checks_all aca
                         ON ipa.check_id = aca.check_id)
             ON     i1.invoice_id = ipa.invoice_id
           LEFT JOIN ap_supplier_sites_all ssa,
             ON i1.vendor_site_id = ssa.vendor_site_id
    WHERE  NVL(substr(upper(translate(i1.invoice_num,'a!@#\/-_%^&*.','a')),
                1,:P_MATCH_LENGTH),'NomatchKluDge1')
               = NVL(substr(upper(translate(i2.invoice_num,'a!@#\/-_$%^&*.','a')),
                1,:P_MATCH_LENGTH),'abcdefghijklm')
    AND    i1.cancelled_date IS NULL
    AND    i2.cancelled_date IS NULL
    AND    aida.distribution_line_number = 1
    AND    aida.INVOICE_LINE_NUMBER = 1
    AND    ail.LINE_NUMBER = 1
    AND    lc.lookup_type  = 'INVOICE TYPE'
    AND    i1.invoice_id = 123456
    ORDER BY upper(v.vendor_name),
             NVL(substr(upper(translate(i1.invoice_num,'a!@#\/-_$%^&*.','a')),
              1,:P_MATCH_LENGTH),'abcdefghijklm'),
             upper(i1.invoice_num);I dislike queries in the SELECT clause like the one you have to get RELEASE_NUM. One thing in particular that I see about this on is that this appears to be the only place that anything from the PO_HEADERS_ALL table is used. PO_HEADERS_ALL is only in the query pulled in by the AP_INVOICE_LINES_ALL table. Since the JOIN column used for that is PO_HEADER_ID and that's the same one used in the SELECT clause query, do you really even need the PO_HEADERS_ALL table? This would remove one join at least.
    Your query had "AND aida.INVOICE_LINE_NUMBER = 1" and "AND ail.LINE_NUMBER = aida.INVOICE_LINE_NUMBER". The second needn't reference AIDA, I changed it to "AND ail.LINE_NUMBER = 1". It likely won't make a performance impact, but the SQL is clearer.

  • Pl/sql function body returning SQL query - Print function

    Hello all,
    I have pl/sql function body returning SQL query for my reports for my new project that I am developing. We dont have any BI tool or anything for APEX so we use Oracle reports to get the same reports to be printed in PDF format. I had been using SQL function for Reports all these days and grabbing the data using SQL query was easy in Oracle reports. But this time we had atleast 8 fields in search criteria and hence I thouhgt PL/sql function body returning SQL query could be something easy to handle that scenario. We have 11 such reports in our project. Now when we tried to use the same PL/sql function to oracle reports , I was told by one of our Oracle reports expert, that we have to write it into functions and use it in SQL query to get the Reports in Oracle reports. Is there any Easy way to convert the same Pl/SQL function or get a PDF format of the same report in APEX without going thru the much pains of rewriting the whole SQL Query.
    thank you
    Devisri

    Hi,
    give this a go.
    I can't test it as I don't have the tables in my schema.
    create or replace package MK_TEST_PF is
    -- Author  : MK
    -- Created : 21/06/2010 16:30:19
    -- Purpose : FOR LUCY_DISCOVER
    -- Public type declarations
    /*     -- just guess the table row types.....
         -- otherwise it won't compile
         type test_rec is record
              (INV REP.inv%type
              ,cNUMBER REP.cNUMBER%type
              ,OPENDATE REP.OPENDATE%type
              ,TARGETDATE REP.ESTCOMPLETE%type
              ,DATECLOSED REP.COMPLETED%type
              ,STATUS REP.STATUS%type
              ,cCODE REP.cCODE%type
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS REP.CLASS%type
              ,SUMM REP.SUMM%type
              ,AREA REP.AREA%type
         type test_rec is record
              (INV varchar2(4000)
              ,cNUMBER varchar2(4000)
              ,OPENDATE varchar2(4000)
              ,TARGETDATE varchar2(4000)
              ,DATECLOSED varchar2(4000)
              ,STATUS varchar2(4000)
              ,cCODE varchar2(4000)
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS varchar2(4000)
              ,SUMM varchar2(4000)
              ,AREA varchar2(4000)
         type test_tab is table of test_rec;
    -- Public constant declarations
    -- Public variable declarations
    -- Public function and procedure declarations
    end MK_TEST_PF;
    create or replace package body MK_TEST_PF is
    -- Private type declarations
    -- Private constant declarations
    -- Private variable declarations
    -- Function and procedure implementations
         function get_query_f
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              return varchar2
         is
              v_sql VARCHAR2(5000);
         --     v_inv VARCHAR2(100);
         --     v_reg VARCHAR2(100);
         --     v_proarea VARCHAR2(100);
         --     v_status VARCHAR2(100);
         --     v_SIG VARCHAR2(100);
         --     v_disp VARCHAR2(100);
         --     v_coding VARCHAR2(100);
         --     v_inc_sum VARCHAR2(4);
         --     v_word VARCHAR2(4000);
              v_wildcard VARCHAR2(2000);
         --     v_timeframe VARCHAR2(100);
         --     v_rec VARCHAR2(5);
              v_record VARCHAR2(5);
              v_open VARCHAR2(100);
              v_closed VARCHAR2(100);
              v_PEND VARCHAR2(100);
              v_refSIG VARCHAR2(100);
              v_refreg VARCHAR2(100);
              v_refother VARCHAR2(100);
              v_y varchar2(100);
         BEGIN
              --v_inv := UPPER(v('P44_INV')) ;
              v_record := 'R%';
              v_wildcard := '%';
              v_open := 'OPEN';
              v_closed := 'CLOSED';
              v_PEND := 'PEND';
              v_refSIG := 'REF - SIG';
              v_refreg := 'REF - CLASS';
              v_refother := 'REF - OTHER';
              v_y := 'Y';
              v_sql := 'SELECT REP.INV as INV, REP.cNUMBER as cNUMBER, REP.OPENDATE as OPENDATE,
              REP.ESTCOMPLETE as TARGETDATE, REP.COMPLETED as DATECLOSED, REP.STATUS as STATUS,
              REP.cCODE as cCODE, apex_item.checkbox(1,REP.line,null,'''||v_y||''') line , apex_item.checkbox(1,REP.SIG,null,'''||v_y||''') SIGc ,
              REP.CLASS as CLASS, REP.SUMM as SUMM, REP.AREA as AREA from REP where 1=1';
              IF p_rec is not null then
                   IF p_rec = 'E' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) not like '''||v_record||'''';
                   ELSIF p_rec = 'D' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) like '''||v_record||'''';
                   ELSIF p_rec = 'I' then
                        v_sql := v_sql|| ' and REP.cnumber = REP.cnumber ';
                   end if ;
              end if ;
              IF upper(p_status) not like '%NULL%' then
                   IF upper(p_status) like '%OPEN%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_open||'''';
                   ELSIF upper(p_status) like '%CLOSED%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_closed||'''';
                   ELSIF upper(v_PEND) like '%PEND%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_PEND||'''';
                   ELSIF upper(v_refSIG) like '%REF - SIG%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refSIG||'''';
                   ELSIF upper(v_refreg) like '%REF - CLASS%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refreg||'''';
                   ELSIF upper(v_refother) like '%REF - OTHER%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refother||'''';
                   END IF ;
              END IF ;
              IF p_inv = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.INV),'''||p_inv||''') > 0';
              END IF ;
              IF p_reg = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.CLASS),'''||p_reg||''') > 0';
              END IF ;
              IF p_proarea = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.AREA),'''||p_proarea||''') > 0';
              END IF ;
              IF p_disp = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.disposition),'''||p_disp||''') > 0';
              END IF ;
              IF p_coding = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.ccode),'''||p_coding||''') > 0';
              END IF ;
              IF p_SIG = ' ' THEN
                   v_sql := v_sql||' AND instr(upper(REP.SIG),'''||p_SIG||''') > 0';
              END IF ;
              IF p_word is not null then
                   v_sql := v_sql|| ' and
                   instr(upper(REP.SUMM),
                   upper(nvl('''||p_WORD_IN_SUMM||''',REP.SUMM))) > 0';
              end if ;
              If p_timeframe is not null then
                   if upper(p_timeframe) = 'OPEN' then
                   v_sql := v_sql|| ' and to_date(REP.opendate) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'CLOSED' then
                   v_sql := v_sql|| ' and to_date(REP.completed) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'EST' then
                   v_sql := v_sql|| ' and to_date(REP.estcomplete) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   end if;
              end if;
              v_sql := v_sql ||' order by REP.INV ';
              return v_sql;
         end get_query_f;
         function test_pf
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              RETURN test_tab PIPELINED
         is
              type test_c is ref cursor;
              v_row test_tab;
              v_sql varchar2(4000);
              v_cursor test_c;
         begin
              v_sql := get_query_f
                   (p_inv
                   ,p_reg
                   ,p_proarea
                   ,p_disp
                   ,p_coding
                   ,p_status
                   ,p_SIG
                   ,p_inc_sum
                   ,p_word
                   ,p_timeframe
                   ,p_rec
                   ,p_WORD_IN_SUMM
                   ,p_ON_AFTER
                   ,p_ON_BEFORE
              open v_cursor for v_sql;
              fetch v_cursor bulk collect into v_row;
              close v_cursor;
              for i in 1 .. v_row.count loop
                   pipe row (v_row(i));
              end loop;
              return;
         end test_pf;
    end MK_TEST_PF;
    /Regards
    Michael

  • Command the execute sql query and does not clean up data in Table

    Hi Team
    I have an SP, which writes source and target data to Temp Tables and runs except query to get mismatch details
    I am using Exec command to execute source query that writes data to Temp Table, once I execute query using Exec, data is written and immediately #temp table is cleaned, now I cannot use #temp table for comparition.
    Is there any way to execute sql query in SP without using EXEC and will hold the data in temp table.

    You need to create temp table before EXEC statement and rewrite your dynamic query also as below
    declare @source_Sql nvarchar(1000)
    ,@target_Sql nvarchar(1000)
    create table #TempTable1 (name nvarchar(10))
    create table #TempTable2 (name nvarchar(10))
    set @source_Sql = 'INSERT INTO #TempTable1 SELECT [Name] from Employee'
    set @target_Sql = 'INSERT INTO #TempTable2 SELECT [Name] from Employee2'
    EXEC (@source_Sql)   
    EXEC (@target_Sql)             
    select * from #TempTable1 
     Except 
    select * from #TempTable2

  • Minus operator versus 'not exists' for faster SQL query

    Hi everybody,
    Does anyone know if rewriting a query to use the MINUS operator instead of using NOT EXISTS in the query is faster, giving all else is the same?
    Thanks very much!
    Bill Loggins
    801-971-6837
    [email protected]

    It really depends on a bunch of factors.
    A MINUS will do a full table scan on both tables unless there is some criteria in the where clause of both queries that allows an index range scan. A MINUS also requires that both queries have the same number of columns, and that each column has the same data type as the corresponding column in the other query (or one convertible to the same type). A MINUS will return all rows from the first query where there is not an exact match column for column with the second query. A MINUS also requires an implicit sort of both queries
    NOT EXISTS will read the sub-query once for each row in the outer query. If the correlation field (you are running a correlated sub-query?) is an indexed field, then only an index scan is done.
    The choice of which construct to use depends on the type of data you want to return, and also the relative sizes of the two tables/queries. If the outer table is small relative to the inner one, and the inner table is indexed (preferrable a unique index but not required) on the correlation field, then NOT EXISTS will probably be faster since the index lookup will be pretty fast, and only executed a relatively few times. If both tables a roughly the same size, then MINUS might be faster, particularly if you can live with only seeing fields that you are comparing on.
    For example, if you have two tables
    EMPLOYEE
    EMPID      NUMBER
    NAME       VARCHAR2(45)
    JOB        VARCHAR2(45)
    HIRE_DATE  DATE
    and
    RETIREE
    EMPID      NUMBER
    NAME       VARCHAR2(45)
    RET_DATE   DATEIf you wanted to see if you had retirees that were not in the employee table, then you could use either MINUS or NOT EXISTS (or even NOT IN, but you didn't ask). However you could possibly get different results.
    SELECT empid,name
    FROM retirees
    MINUS
    SELECT empid,name
    FROM employeeswould show retirees not in the emp table, but it would also show a retiree who had changed their name while retired. A safer version of the above using MINUS would be
    SELECT empid,name
    FROM retirees
    WHERE empid IN (SELECT empid
                    FROM retirees
                    MINUS
                    SELECT empid
                    FROM employees)A full scan of retirees, a full scan of employees (Assuming indexes on both, then maybe an index fast full scan) and two sorts for the minus, at best an index probe then table access by rowid on retirees, possibly a full scan of retirees for the outer query.
    Assuming that employees is indexd on empid then
    SELECT empid,name
    FROM retirees
    WHERE NOT EXISTS (SELECT 1
                      FROM employees
                      WHERE retirees.empid = employees.empid)requires a full scan of retirees and an index access into employees index for each row.
    As with most things SQL, the only real way to tell is to benchmark.
    HTH
    John

  • Please help rewrite the query

    Hi ,
    Below query is taking more time (4mins) for 41 rows returning and there is no full table scan .Can some one help to rewrite the query.
    SELECT
              esma.candidate AS candidate_additional_sample,
              ccr.raw_mark,
              ccr.split_session_year AS year,
              ccr.split_session_month AS month,
              ccr.paper_code,
              ccr.assessment_school AS school_code,
              get_cand_session_number(ccr.split_session_year,ccr.split_session_month,ccr.candidate) AS candidate_session_number,
              ccr.candidate AS candidate_code,
              c.firstname AS candidate_firstname,
              c.lastname AS candidate_lastname,
              ema.moderator_code,
              ema.examiner_code,
              csr.self_taught
             FROM
              ibis.candidate_component_reg ccr
            INNER JOIN ibis.candidate_examiner_allocation cea
               ON ccr.split_session_year= cea.year
              AND ccr.split_session_month=cea.month
              AND ccr.assessment_school=cea.assessment_school
              AND ccr.paper_code= cea.paper_code
              AND ccr.candidate     =        cea.candidate
            INNER JOIN ibis.examination_paper ep
              ON ccr.split_session_year= ep.year
              AND ccr.split_session_month=ep.month
              AND ccr.paper_code=ep.paper_code
            INNER JOIN ibis.examiner_moderator_allocation ema
              ON ema.year =cea.year
              AND ema.month =cea.month
              AND ema.no_lang_code=ep.no_lang_code
              AND ema.examiner_code=cea.examiner_code
              AND ema.year =ccr.split_session_year
              AND ema.month =ccr.split_session_month
            INNER JOIN ibis.candidate_subject_registration csr
              ON ccr.split_session_year=csr.year
              AND ccr.split_session_month=csr.month
              AND ccr.main_school=csr.main_school
              AND ccr.candidate=csr.candidate
              AND ccr.subject=csr.subject
              AND ccr.subject_option=csr.subject_option
              AND ccr.lvl=csr.lvl
              AND ccr.language=csr.language 
            INNER JOIN ibis.candidate c
              ON ccr.candidate=c.candidate
            LEFT OUTER JOIN  ibis.exam_sample_mark_additional esma
              ON ccr.split_session_year = esma.year
              AND ccr.split_session_month  = esma.month
              AND ep.no_lang_code = esma.nolang_code
              AND ccr.candidate = esma.candidate
            WHERE
                  ccr.split_session_year=:v_year
              AND ccr.split_session_month=:v_month
              AND ccr.subject=:v_subject
              AND ccr.subject_option=nvl(:v_subject_option,ccr.subject_option)
              AND ccr.language=nvl(:v_language, ccr.language)
              AND ccr.component=:v_component
              AND ccr.lvl=:v_lvl
              AND ccr.raw_mark IS NOT NULL          
              AND cea.examiner_code  = :v_examiner_code
              AND ((ccr.sampled='Y'
                      AND csr.self_taught='N'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND sc.assessment_type='INTERNAL'
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND NOT EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y')
                      AND NOT EXISTS (SELECT 1 FROM ibis.school_sample_mark ssm
                                      WHERE ssm.year= ccr.split_session_year
                                        AND ssm.month  = ccr.split_session_month
                                        AND ssm.paper_code  = ccr.paper_code
                                        AND ssm.candidate =ccr.candidate
                                        AND ssm.examiner_sample = 'Y'))
                  OR (ccr.sampled='N'
                      AND csr.self_taught='Y'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND NOT EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y'))
                  OR (ccr.sampled='N'
                      AND EXISTS (SELECT 1 FROM ibis.subject_component sc
                                  WHERE sc.assessment_method_id = 11
                                    AND ccr.split_session_year=sc.year
                                    AND ccr.split_session_month=sc.month
                                    AND ccr.paper_code=sc.paper_code
                                    AND ccr.subject=sc.subject
                                    AND ccr.subject_option=sc.subject_option
                                    AND ccr.lvl=sc.lvl
                                    AND ccr.language=sc.language
                                    AND ccr.component=sc.component)
                      AND EXISTS (SELECT 1 FROM ibis.cw_portfolio_template cpt
                                      WHERE ccr.split_session_year = cpt.year
                                        AND ccr.split_session_month = cpt.month
                                        AND ccr.subject = cpt.subject
                                        AND ccr.subject_option = cpt.subject_option
                                        AND ccr.component = cpt.component
                                        AND cpt.combined = 'Y')));
    explain plan
    line 1: SQLPLUS Command Skipped: set linesize 130
    line 2: SQLPLUS Command Skipped: set pagesize 0
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    Plan hash value: 2594643366                                                                                                                                                                                                                                                                                 
    | Id  | Operation                             | Name                           | Rows  | Bytes | Cost (%CPU)| Time     |                                                                                                                                                                                    
    |   0 | SELECT STATEMENT                      |                                |     2 |  1036 |    34   (3)| 00:00:01 |                                                                                                                                                                                    
    |*  1 |  FILTER                               |                                |       |       |            |          |                                                                                                                                                                                    
    |*  2 |   HASH JOIN OUTER                     |                                |     2 |  1036 |    34   (3)| 00:00:01 |                                                                                                                                                                                    
    |   3 |    VIEW                               |                                |     2 |   974 |    32   (0)| 00:00:01 |                                                                                                                                                                                    
    |   4 |     CONCATENATION                     |                                |       |       |            |          |                                                                                                                                                                                    
    |*  5 |      FILTER                           |                                |       |       |            |          |                                                                                                                                                                                    
    |*  6 |       TABLE ACCESS BY INDEX ROWID     | CANDIDATE_SUBJECT_REGISTRATION |     1 |    58 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |   7 |        NESTED LOOPS                   |                                |     1 |   485 |    16   (0)| 00:00:01 |                                                                                                                                                                                    
    |   8 |         NESTED LOOPS                  |                                |     1 |   427 |    13   (0)| 00:00:01 |                                                                                                                                                                                    
    |   9 |          NESTED LOOPS                 |                                |     1 |   357 |    11   (0)| 00:00:01 |                                                                                                                                                                                    
    |  10 |           NESTED LOOPS                |                                |     1 |   129 |     8   (0)| 00:00:01 |                                                                                                                                                                                    
    |  11 |            NESTED LOOPS               |                                |     1 |    80 |     5   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 12 |             INDEX RANGE SCAN          | PK_EXAMINER_MODERATOR_ALLOC    |     1 |    39 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 13 |             INDEX RANGE SCAN          | RFL_EP1                        |     1 |    41 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  14 |            TABLE ACCESS BY INDEX ROWID| CANDIDATE_EXAMINER_ALLOCATION  |     1 |    49 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 15 |             INDEX RANGE SCAN          | CANDIDATE_ALLOCATION_EXAMINER  |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 16 |           TABLE ACCESS BY INDEX ROWID | CANDIDATE_COMPONENT_REG        |     1 |   228 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 17 |            INDEX RANGE SCAN           | SPLIT_SESSION_CANDIDATE        |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  18 |          TABLE ACCESS BY INDEX ROWID  | CANDIDATE                      |     1 |    70 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 19 |           INDEX UNIQUE SCAN           | CANDIDATE_PK                   |     1 |       |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 20 |         INDEX RANGE SCAN              | Y_M_CAND_SUBJ_LVL_OPTION       |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 21 |      FILTER                           |                                |       |       |            |          |                                                                                                                                                                                    
    |* 22 |       TABLE ACCESS BY INDEX ROWID     | CANDIDATE_SUBJECT_REGISTRATION |     1 |    58 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |  23 |        NESTED LOOPS                   |                                |     1 |   485 |    16   (0)| 00:00:01 |                                                                                                                                                                                    
    |  24 |         NESTED LOOPS                  |                                |     1 |   427 |    13   (0)| 00:00:01 |                                                                                                                                                                                    
    |  25 |          NESTED LOOPS                 |                                |     1 |   357 |    11   (0)| 00:00:01 |                                                                                                                                                                                    
    |  26 |           NESTED LOOPS                |                                |     1 |   129 |     8   (0)| 00:00:01 |                                                                                                                                                                                    
    |  27 |            NESTED LOOPS               |                                |     1 |    80 |     5   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 28 |             INDEX RANGE SCAN          | PK_EXAMINER_MODERATOR_ALLOC    |     1 |    39 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 29 |             INDEX RANGE SCAN          | RFL_EP1                        |     1 |    41 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  30 |            TABLE ACCESS BY INDEX ROWID| CANDIDATE_EXAMINER_ALLOCATION  |     1 |    49 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 31 |             INDEX RANGE SCAN          | CANDIDATE_ALLOCATION_EXAMINER  |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 32 |           TABLE ACCESS BY INDEX ROWID | CANDIDATE_COMPONENT_REG        |     1 |   228 |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 33 |            INDEX RANGE SCAN           | SPLIT_SESSION_CANDIDATE        |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |  34 |          TABLE ACCESS BY INDEX ROWID  | CANDIDATE                      |     1 |    70 |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 35 |           INDEX UNIQUE SCAN           | CANDIDATE_PK                   |     1 |       |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 36 |         INDEX RANGE SCAN              | Y_M_CAND_SUBJ_LVL_OPTION       |     1 |       |     2   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 37 |    INDEX RANGE SCAN                   | EXAM_SAMP_MARK_ADD_IOT_PK      |    36 |  1116 |     1   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 38 |   TABLE ACCESS BY INDEX ROWID         | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 39 |    INDEX RANGE SCAN                   | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 40 |    TABLE ACCESS BY INDEX ROWID        | SCHOOL_SAMPLE_MARK             |     1 |    34 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 41 |     INDEX RANGE SCAN                  | CAND_PAPER_YEAR_MONTH          |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 42 |     TABLE ACCESS BY INDEX ROWID       | SUBJECT_COMPONENT              |     1 |    96 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 43 |      INDEX RANGE SCAN                 | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 44 |      TABLE ACCESS BY INDEX ROWID      | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 45 |       INDEX RANGE SCAN                | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 46 |       TABLE ACCESS BY INDEX ROWID     | SUBJECT_COMPONENT              |     1 |    87 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 47 |        INDEX RANGE SCAN               | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 48 |        TABLE ACCESS BY INDEX ROWID    | SUBJECT_COMPONENT              |     1 |    87 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 49 |         INDEX RANGE SCAN              | SUBJECT_COMPONENT_PK           |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 50 |         TABLE ACCESS BY INDEX ROWID   | CW_PORTFOLIO_TEMPLATE          |     1 |    46 |     4   (0)| 00:00:01 |                                                                                                                                                                                    
    |* 51 |          INDEX RANGE SCAN             | YEAR_MON_PORTFOLIO_TEMPLATE    |     1 |       |     3   (0)| 00:00:01 |                                                                                                                                                                                    
      Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       1 - filter("from$_subquery$_011"."SAMPLED"='Y' AND "from$_subquery$_011"."SELF_TAUGHT"='N' AND  NOT EXISTS                                                                                                                                                                                               
                  (SELECT /*+ */ 0 FROM "IBIS"."CW_PORTFOLIO_TEMPLATE" "CPT" WHERE "CPT"."COMPONENT"=:B1 AND                                                                                                                                                                                                    
                  "CPT"."SUBJECT_OPTION"=:B2 AND "CPT"."SUBJECT"=:B3 AND "CPT"."MONTH"=:B4 AND "CPT"."YEAR"=:B5 AND                                                                                                                                                                                             
                  "CPT"."COMBINED"='Y') AND  NOT EXISTS (SELECT /*+ */ 0 FROM "IBIS"."SCHOOL_SAMPLE_MARK" "SSM" WHERE                                                                                                                                                                                           
                  "SSM"."MONTH"=:B6 AND "SSM"."YEAR"=:B7 AND "SSM"."PAPER_CODE"=:B8 AND "SSM"."CANDIDATE"=:B9 AND                                                                                                                                                                                               
                  "SSM"."EXAMINER_SAMPLE"='Y') AND  EXISTS (SELECT /*+ */ 0 FROM "IBIS"."SUBJECT_COMPONENT" "SC" WHERE                                                                                                                                                                                          
                  "SC"."COMPONENT"=:B10 AND "SC"."SUBJECT_OPTION"=:B11 AND "SC"."LANGUAGE"=:B12 AND "SC"."LVL"=:B13 AND                                                                                                                                                                                         
                  "SC"."SUBJECT"=:B14 AND "SC"."MONTH"=:B15 AND "SC"."YEAR"=:B16 AND "SC"."PAPER_CODE"=:B17 AND                                                                                                                                                                                                 
                  "SC"."ASSESSMENT_METHOD_ID"=11 AND "SC"."ASSESSMENT_TYPE"='INTERNAL') OR "from$_subquery$_011"."SAMPLED"='N'                                                                                                                                                                                  
                  AND "from$_subquery$_011"."SELF_TAUGHT"='Y' AND  NOT EXISTS (SELECT /*+ */ 0 FROM                                                                                                                                                                                                             
                  "IBIS"."CW_PORTFOLIO_TEMPLATE" "CPT" WHERE "CPT"."COMPONENT"=:B18 AND "CPT"."SUBJECT_OPTION"=:B19 AND                                                                                                                                                                                         
                  "CPT"."SUBJECT"=:B20 AND "CPT"."MONTH"=:B21 AND "CPT"."YEAR"=:B22 AND "CPT"."COMBINED"='Y') AND  EXISTS (SELECT                                                                                                                                                                               
                  /*+ */ 0 FROM "IBIS"."SUBJECT_COMPONENT" "SC" WHERE "SC"."COMPONENT"=:B23 AND "SC"."SUBJECT_OPTION"=:B24 ANDEdited by

    Can you please post the following scripts:
    1. Tables structure (with all indexes & constraints)
    2. Tables data
    3. SQL trace file
    possibly everything that one can need to regenerate the scenario on his own DB...
    OR
    spend some time with Oracle Docs on Performance Tuning and then resolve it yourself.
    Regards,
    Ankit Rathi
    http://theoraclelog.blogspot.in

  • Need help with sql query dates

    Hi,
    I have a sql query where i need to extract some info between given dates. The where clause of this query is as follows:
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :P_DATE_FROM
    AND CPD_VOUCHER_DATE < (:P_DATE_TO+1)
    When i execute the query in toad, i can view the data but not the execution plan.It gives an error ORA-00932-Inconsistent Datatypes.
    But when i remove (+1) from :P_DATE_TO, i can c the execution plan and data. Will the data be different from the previous one.
    Please suggest how to rewrite the query.

    Can you please give it a try?
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :to_date(P_DATE_FROM)
    AND CPD_VOUCHER_DATE < (to_date(:P_DATE_TO)+1) Regards

  • How to write SQL query to flatten the hierarchy

    Hi,
    I have person table which has recursive hierarchy and I wish to flatten it upto 5 levels.
    I am using Oracle10g and I have written following query to flatten the hierarchy
    SELECT
    ID,
    level lvl,
    REGEXP_SUBSTR (SYS_CONNECT_BY_PATH (fname||' '||lname, '/'), '[^/]+', 1, 1) AS level_1,
    REGEXP_SUBSTR (SYS_CONNECT_BY_PATH (fname||' '||lname, '/'), '[^/]+', 1, 2) AS level_2,
    REGEXP_SUBSTR (SYS_CONNECT_BY_PATH (fname||' '||lname, '/'), '[^/]+', 1, 3) AS level_3,
    REGEXP_SUBSTR (SYS_CONNECT_BY_PATH (fname||' '||lname, '/'), '[^/]+', 1, 4) AS level_4,
    REGEXP_SUBSTR (SYS_CONNECT_BY_PATH (fname||' '||lname, '/'), '[^/]+', 1, 5) AS level_5
    FROM cmt_person
    CONNECT BY manager_id = PRIOR id
    and level<=5
    The person table have more than a million records.
    Here I am getting the correct output but this query is taking a lot of time to run.
    I am looking at a SQL query without use of connect by to get the required output.
    To recreate the issue, you can use this query in HR schema of Oracle and use Employees table.
    Any help would be greatly appreciated.
    Thanks,
    Raghvendra

    I tried to rewrite the query without using regular expression and connect by. Here is the code:
    SELECT
    cmt_person.id ,
    cmt_person.fname as mgr1,
    case when cmt_person2.manager_id=cmt_person.id then (cmt_person2.fname ) end as mgr2,
    case when cmt_person3.manager_id=cmt_person2.id then (cmt_person3.fname ) end as mgr3,
    case when cmt_person4.manager_id=cmt_person3.id then cmt_person4.fname end as mgr4,
    case when cmt_person5.manager_id=cmt_person4.id then cmt_person5.fname end as mgr5
    FROM
    cmt_person,
    cmt_person cmt_person2,
    cmt_person cmt_person3,
    cmt_person cmt_person4,
    cmt_person cmt_person5
    WHERE
    cmt_person2.manager_id(+)=cmt_person.id and
    cmt_person3.manager_id(+)=cmt_person2.id and
    cmt_person4.manager_id(+)=cmt_person3.id and
    cmt_person5.manager_id(+)=cmt_person4.id
    order by 2,3,4
    I got following output:
    emplo000000000200100     Bobby     Khasha     Rahul     Rajesh     
    emplo000000000200099     Bobby     Khasha     Rahul     Ajay     
    emplo000000000200101     Bobby     Khasha     Rahul     Swati     
    emplo000000000200320     Bobby     Khasha     Rahul     Jinesh     
    emplo000000000201231     Bobby     Khasha     Test123          
    emplo000000000201230     Bobby     Khasha     User1_Domain          
    emplo000000000201227     Bobby     Khasha     User1_World          
    emplo000000000200104     Bobby     Khasha     Yitzik     Natalia     
    emplo000000000200103     Bobby     Khasha     Yitzik     Andrew     
    total 9 rows
    But this is partially correct output. I want output like this:
    emplo000000000200097          Bobby                    
    emplo000000000200087          Bobby     Khasha               
    emplo000000000200102          Bobby     Khasha     Yitzik          
    emplo000000000200103          Bobby     Khasha     Yitzik     Andrew     
    emplo000000000200104          Bobby     Khasha     Yitzik      Natalia     
    emplo000000000201227          Bobby     Khasha     User1_World          
    emplo000000000201231          Bobby     Khasha     Test123          
    emplo000000000201230          Bobby     Khasha     User1_Domain          
    emplo000000000200098          Bobby     Khasha     Rahul          
    emplo000000000200099          Bobby     Khasha     Rahul     Ajay     
    emplo000000000200100          Bobby     Khasha     Rahul     Rajesh     
    emplo000000000200320          Bobby     Khasha     Rahul     Jinesh     
    emplo000000000200101          Bobby     Khasha     Rahul     Swati     
    total 13 rows
    Do you know what I should do to get this output.
    Thanks,
    Raghvendra

Maybe you are looking for

  • RAPERB2000 problem / Missing profit center

    Hi We have the new GL with balancing field profit center active. We posted an asset disposal w/o revenue. RAPERB2000 cannot post the difference between leading and non-leading ledger: balancing field profit center is not filled. In a different compan

  • Portal 11g Upgrade (11.1.1.6) with SSO (10.1.4.3)

    I have just performed a Portal upgrade from 10g to 11g which is integrated with SSO (10.1.4.3) which is hosted on a separate host from portal. All components start sucessfully but I am getting the following error in my SSO Apache error_log when I att

  • How to automatically show print dialog as soon as pdf opens?

    A pdf template was created using adobe livecycle, then the final pdf is created using pdfMerger. Is there a way to invoke the print dialog as soon as the pdf is open?

  • To find whether current user has SAP_ALL profile or not.

    Hi all, Can anyone tell me that whether is there any method by which I can pass the user id and can know whether that user has the SAP_ALL profile or not. The above is done by using the transaction SU01,but I need the ABAP code that is being used in

  • Make my header columns tall and narrow and place the text sideways

    I'd like the header columns to be very narrow and tall and the text to be sideways.  I can't figure out how to make it work.  My temporary fix is to place textboxes over the columns, but they don't "belong" to the column and don't move with the table