Outter-Join with requirement for sub-query

I am working on a view that needs to return 1 record per payment date within the primary payment table.
Part of the information that is to be returned in this row comes from a date-controlled table containing superannuation information. This data may or may not be present, requiring an outer-join. The final problem is that there may be multiple rows in this superannuation table requiring me to retrieve the record with the most recent start date, prior to the payment date. This is where I'm breaking down currently as I cannot outer-join to a sub-query.
I had an idea that I could create an inline view of the superannuation table with 1 row for each of the last 365 days (The reports that will be built off the view are always run within 1-2 months of the payment date), with the date and either the required information or blanks if it did not exist. This would avoid me requiring an outer-join as I could just join on the payment date to the date in the inline query and return whatever data was there.
I'm pretty sure I should be able to do this with analytics rather than creating a date table, by restricting the rows to 365, then havign a column that is effectively the previous column - 1. Unfortunately I'm fairly new to analytics and find the Oracle documentation hard to decipher.
Can anyone help with this or perhaps suggest an alternate solution?

please don't do that. that's the most pathetic way generate rows. all_objects is a very nasty view, and oracle reserves the right to merge the view into the rest of your query, making performance less than you had hoped for. how about this instead:
select ...
from (
select trunc(sysdate-rownum+1) super_date
from dual
connect by level < = 365 ) dates,
your_table_here
where dates.super_date = your_column (+)
...

Similar Messages

  • SQL Server Multiple JOINS with Table Value Function - query never ends

    I have a query with 4 joins using a table value function to get the data and when I execute it the query never ends.
    Issue Details 
    - Table value function 
        CREATE FUNCTION [dbo].[GetIndicator] 
          @indicator varchar(50),
          @refDate datetime
    RETURNS 
    TABLE
    AS
    RETURN
    SELECT
    T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1
    FROM TABLE2 T2
    JOIN TABLE3 T3
    ON T2.COLFKT3 = T3.Id
    AND T3.ReferenceDate = @RefDate
    AND T3.State != 'Deleted'
    JOIN TABLE4 T4
    ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
    JOIN TABLE1 T1
    ON T2.COLFKT1=T1.Id
    - Query
        DECLARE @RefDate datetime
    SET @RefDate = '30 April 2014 23:59:59'
    SELECT DISTINCT OTHERTABLE.Id As Id
    FROM 
    GetIndicator('ID#1_0#INDICATOR_X',@RefDate) AS OTHERTABLE
    JOIN GetIndicator('ID#1_0#INDICATOR_Y',@RefDate) AS YTABLE  
    ON OTHERTABLE.SomeId=YTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=YTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_Z',@RefDate) AS ZTABLE
    ON OTHERTABLE.SomeId=ZTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=ZTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_W',@RefDate) AS WTABLE 
    ON OTHERTABLE.SomeId=WTABLE.SomeId
    AND OTHERTABLE.DateOfEntry=WTABLE.DateOfEntry
    JOIN GetIndicator('ID#1_0#INDICATOR_A',@RefDate) AS ATABLE  
    ON OTHERTABLE.SomeId=ATABLE.SomeId
    AND OTHERTABLE.DateOfEntry=ATABLE.DateOfEntry
    Other details:
    - SQL server version: 2008 R2
    - If I execute the table function code outside the query, with the same args, the execution time is less the 1s.
    - Each table function call return between 250 and 500 rows.

    Hi,
    Calling function in general is a costly query. And definitely joining with a function 5 times in not an efficient one.
    1. You can populate the results for all parameters in a CTE or table variable or temporary table and join (instead of funtion) for different parameters
    2. Looks like you want fetch the IDs falling to different indicators for the same @Refdate. You can try something like this
    WITH CTE
    AS
    SELECT
    T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1, T4.Name
    FROM TABLE2 T2
    JOIN TABLE3 T3
    ON T2.COLFKT3 = T3.Id
    AND T3.ReferenceDate = @RefDate
    AND T3.State != 'Deleted'
    JOIN TABLE4 T4
    ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
    JOIN TABLE1 T1
    ON T2.COLFKT1=T1.Id
    SELECT * FROM CTE WHERE Name = 'ID#1_0#INDICATOR_X' AND Name = 'ID#1_0#INDICATOR_Y' AND Name = 'ID#1_0#INDICATOR_Z' AND Name = 'ID#1_0#INDICATOR_W' AND Name = 'ID#1_0#INDICATOR_A' AND ReferenceDate = @RefDate.
    Or you can even simplify more depends on your requirement.
    Regards,
    Brindha.

  • See my query problem for sub query

    hi master
    Sir see my query
    select lpad(' ',2*(level-1)) || to_char(chartofacc.child),parent,accid as accounted ,title,
    case when fstatus=1 then
    (select sum(drbal) from accbal where parent = accounted)
    when fstatus is null then
    (select drbal from accbal where accid = accounted)
    end subtotal
    from chartofacc
    start with chartofacc.parent is null
    connect by prior chartofacc.child = chartofacc.parent order by chartofacc.accid
    I try but not success how I pass main query value or code in sub query or inner query
    My requirement is inner query get total from accbal table how have accid that in main query accid or accounted
    How I pass main query value or accid code to inner query and inner query give result as per main query accid
    How I get subtotal and total by one query
    Please give me idea or code
    Thanking you
    aamir

    You could write your main SELECT statement as inline view or use the WITH clause, like this:
    WITH ctf AS (SELECT LPAD (' ', 2 * (LEVEL - 1)) || TO_CHAR (chartofacc.CHILD), PARENT,
                        accid AS accounted, title,
                   FROM chartofacc
                  START WITH chartofacc.PARENT IS NULL
                  CONNECT BY PRIOR chartofacc.CHILD = chartofacc.PARENT
                  ORDER BY chartofacc.accid
    SELECT ctf.*,
           CASE WHEN fstatus = 1
                THEN (SELECT SUM (drbal)
                        FROM accbal
                       WHERE PARENT = accounted)
                WHEN fstatus IS NULL
                THEN (SELECT drbal
                        FROM accbal
                       WHERE accid = accounted)
           END subtotal
      FROM ctf
    not tested
    C.

  • Tuning required for the query

    Hi,
    I am just wondering what could be the best SQL for the following scenario.
    Table 1 Table2
    COL1 COL2 COL3 COL1 COL2 COL3
    AAA 123 10 AAA 123 12
    AAA 123 12
    AAA 123 14
    AAA 456 10
    AAA 456 12
    AAA 456 14
    Given the above data, I want only the AAA/123/10 and AAA/123/14 records from table1, and leave the others alone.
    The tables are huge (200 million) and indexed on all the three columns and my SQL is taking much time to complete.
    SQL i have used
    select col1, col2, col3 from (
    select a.col1, a.col2, a.col3, b.col3 col4 from
    table1 a
    left join
    table2 b
    on
    a.col1 = b.col1 and
    a.col2 = b.col2 and
    a.col3 = b.col3
    where exists (select 1 from table2 c where a.col1 = c.col1 and a.col2 = c.col2)
    ) x
    where x.col4 is null
    Can anyone give me better solution than this?

    Depending on your data, there is a good possibility that the intermediate result set, after the outerjoin from table1 to table2, is even more huge than the original tables. This might impact the time it takes to process your query in a negative way.
    The next query does something similar, but with a smaller intermediate result sets and is therefore probably a bit faster. At least it's worth the try. Please let us know the impact.
    SQL> select t1.col1
      2       , t1.col2
      3       , t1.col3
      4    from table1 t1
      5   where exists
      6         ( select null
      7             from table2 t2
      8            where t2.col1 = t1.col1
      9              and t2.col2 = t1.col2
    10         )
    11   minus
    12  select t2.col1
    13       , t2.col2
    14       , t2.col3
    15    from table2 t2
    16  /
    COL       COL2       COL3
    AAA        123         10
    AAA        123         14
    2 rows selected.Regards,
    Rob.

  • Is there any tool or method to find the exact disk space/memory required for a query to execute in certain time

    Hi,
    We have SSIS Package, which in-turn executes some Stored procedures . 
    This Package runs fine at certain time, say 30 minutes which is acceptable. But sometimes, it takes around 1.5 hr. There was no modification done to the package, and the amount of data handled by the package is also same.
    I have a doubt that some other big process may be running in parallel when this package is getting executed.
    All the Databases are on D drive in the server and currently there is 140 GB free space out of 1 TB.
    Now, using sp_who2 I can check what are the big processes which are running in parallel when this package is getting executed and get their Disk I/O.   
    Now having these information, is there any way to determine, amount of space/memory required to execute a particular query in 30 minutes.
    Or to put a question in other way, I have a query and I know its acceptable execution time(30 min). Now is there any way to determine the criteria to get that execution time.
    NOTE: The query is optimized and required indexes are created. It was running fine, until 1 week back. Suddenly the execution time has increased.
    Can some one please help me in this. Please let me know if you need any further information on this.
    Also whenever these jobs are running, sometimes job activity monitor and SSMS gets frozen. Any idea what does this indicate?
    Thanks in advance,
    Raksha

    Perhaps blocking?
    Take a look at Adam's great stored procedure to see who is running on the server
    Who Is Active? v10.00 (2010-10-21)
    (C) 2007-2010, Adam Machanic
    Feedback: mailto:[email protected]
    Updates: http://sqlblog.com/blogs/adam_machanic/archive/tags/who+is+active/default.aspx
    "Beta" Builds: http://sqlblog.com/files/folders/beta/tags/who+is+active/default.aspx
    License: 
    Who is Active? is free to download and use for personal, educational, and internal 
    corporate purposes, provided that this header is preserved. Redistribution or sale 
    of Who is Active?, in whole or in part, is prohibited without the author's express 
    written consent.
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Help with doing SELECT sub query within the SET of an UPDATE statement

    After doing some research, it appears as if it's possible to use a SELECT subquery in the SET of an UPDATE statement.  i did find some examples and here is my code, however when I click the "check" button it's saying the field (my entire select subquery) is unknown and neither in one of the specified tables or defined by a "DATA".  Do I have a syntax issue or is there another reason why it's not taking this as a valid statement?  Thanks for the help!
    LOOP AT IT_DATA
    UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL )
                            FROM /BIC/AZDP_O0140
                            WHERE MATERIAL EQ IT_DATA-MATERIAL
                            GROUP BY MATERIAL).
    ENDLOOP.

    my Update does indeed have a WHERE clause but because of the issue i'm having, all my criteria in my WHERE is black text in the ABAP editor.  The editor doesn't even recognize the keywords "WHERE" or "EQ".  Below is my entire statement which contains all WHERE criteria in both the Update and the Subquery, i've just removed it for testing to help simplify the query and eliminate as many other factors as posisble that may be causing problems:
    LOOP AT IT_DATA.
       UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL ) FROM /BIC/AZDP_O0140
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL
        GROUP BY MATERIAL)
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL.
    ENDLOOP.
    i should also mention the sources i found were not within the SAP Library but instead on other third-party ABAP websites.  so because i was having issues i wanted to post here to see if anyone else has come up with a working solution.  but if this cannot be done i can likely come up with a solution for my needs using multiple internal tables, this would just have been much easier since i can get a query like this to do what i want in SQL Server.  Thought i could utilize this in ABAP as well.

  • Logic required for select query

    i have a internal table with 4 columns. 3 columns having varrious material numbers. i want to check every material with mara table. its available or not?
    I need to write a single select queary? how to do this?
    My internal table looks like
    matnr     idnrk          s_idnrk          normt
    test10     10UPC3050     F14839030     test.
    i wrotes like below
       select matnr from mara into table
                     i_mara2 for all entries in
                     i_sub_file
                     where matnr =  i_sub_file-matnr and
                           matnr =  i_sub_file-idnrk and
                           matnr = i_sub_file-s_idnrk.
    Its not working, How to manage this? Anyone help this.
    Mohaha

    Hi fill the ranges with ur 3 material numbers.
    and use it in ur select query.
    define a range for mat no.
    ranges : r_matnr for mara-matnr.
    read table or loop with i_sub_file.
      r_matnr-sign = 'I'.
      r_matnr-option = 'EQ'.
      r_matnr-low = 'i_sub_file-matnr.
      append r_matnr. clear r_matnr.
      r_matnr-sign = 'I'.
      r_matnr-option = 'EQ'.
      r_matnr-low = 'i_sub_file-idnrk.
      append r_matnr. clear r_matnr.
      r_matnr-sign = 'I'.
      r_matnr-option = 'EQ'.
      r_matnr-low = 'i_sub_file-s_idnrk.
      append r_matnr. clear r_matnr.
    now in select.
    select matnr from mara into table
    i_mara2  where matnr in r_matnr.

  • Decode with multiple column sub query

    Dear's
    What is the wrong with the query
    select * from common_master
    where
    (company_code,lpad(rtrim(ltrim(bu_code)),12,' ')) IN
    decode ('ADMIN','ADMIN',(select company_code ,lpad(rtrim(ltrim(bu_code)),12,' ') from common_master )
    ,(select company_code ,lpad(rtrim(ltrim(bu_code)),12,' ') from user_system_privs) )
    The error message as
    Error starting at line 16 in command:
    select * from common_master
    where
    (company_code,lpad(rtrim(ltrim(bu_code)),12,' ')) IN
    decode ('ADMIN','ADMIN',(select company_code ,lpad(rtrim(ltrim(bu_code)),12,' ') from common_master )
    ,(select company_code ,lpad(rtrim(ltrim(bu_code)),12,' ') from user_system_privs) )
    Error at Command Line:18 Column:53
    Error report:
    SQL Error: ORA-00920: invalid relational operator
    00920. 00000 - "invalid relational operator"
    *Cause:   
    *Action:
    Dennis

    You can club the columns in where clause and in decode
    like
    select * from common_master
    where
    (company_code || lpad(rtrim(ltrim(bu_code)) || to_char(12) ||' ') IN
    ( select decode ('ADMIN','ADMIN',company_code || lpad(rtrim(ltrim(bu_code)) || to_char(12) || ' ') from common_master ),
    ,company_code || lpad(rtrim(ltrim(bu_code)) || to_char(12) ||' ') from user_system_privs) )
    HTH,
    ~Yogesh

  • Help with creating a sub-query

    Hi,
    I have a table, comprised of three columns: patient_id, observation, and pain_score
    Pat_id, obs_num, pain_score
    12345, 1, 4
    12345, 2, 6
    12345, 3, 8
    98765, 1, 2
    98765, 2, 4
    98765, 3, 6
    I need to see the percent change from observation 1 to observation 3 per patient. So basically I need to isolate the 4 and the 8 pain_score for patient 12345; and the 2 and 6 pain_score for patient 98765. All patients have 3 observation periods.
    Thanks for the help.
    Rich

    test@XE> set echo on
    test@XE>
    test@XE> @test3
    test@XE> --
    test@XE> with t as (
      2    select 12345 as pat_id, 1 as obs_num, 4 as pain_score from dual union all
      3    select 12345, 2, 6 from dual union all
      4    select 12345, 3, 8 from dual union all
      5    select 98765, 1, 2 from dual union all
      6    select 98765, 2, 4 from dual union all
      7    select 98765, 3, 6 from dual)
      8  --
      9  select pat_id,
    10         obs_num,
    11         pain_score,
    12         lead(pain_score) over (partition by pat_id order by obs_num) as next_pain_score,
    13         case obs_num
    14           when 1 then (lead(pain_score) over (partition by pat_id order by obs_num) - pain_score)/pain_score*100||' %'
    15           else null
    16         end as pct_change
    17  from t
    18  where obs_num in (1, 3);
        PAT_ID    OBS_NUM PAIN_SCORE NEXT_PAIN_SCORE PCT_CHANGE
         12345          1          4               8 100 %
         12345          3          8
         98765          1          2               6 200 %
         98765          3          6
    test@XE>
    test@XE>
    test@XE>isotope

  • Help required for the query

    sir
    below query runs fine
    but the probblem is...i am not able to display the figures in the format '999999.99'
    Also please guide me as to make the query short... can i use cursors here?
    i am using 10g
    select
    LBRCODE branch,
    trim(substr(PRDACCTID,1,8)) product,
    sum(case when totsanclimit between 0 and 200000  then
         (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-1",
    SUM( CASE WHEN TOTSANCLIMIT between 0 and 200000 then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE
    0 end) AS"Bkt_1",
    sum(case when totsanclimit between 200001 and 1000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-2",
    SUM(
    CASE WHEN TOTSANCLIMIT between 200001 and 1000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_2",
    sum(case when totsanclimit between 1000001 and 5000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-3",
    SUM(
    CASE WHEN TOTSANCLIMIT between 1000001 and 5000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_3",
    sum(case when totsanclimit between 5000001 and 10000000  then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-4",
    SUM(
    CASE WHEN TOTSANCLIMIT between 5000001 and 10000000
    then
          (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_4",
    sum(case when totsanclimit BETWEEN  10000001 AND 200000000  then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-5",
    SUM(
    CASE WHEN TOTSANCLIMIT  BETWEEN  10000001 AND  200000000
    then
         (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_5",
    sum(case when totsanclimit > 200000000 then
    (Case when  hrk in (13,14) THEN 
              (CASE WHEN bal4 !=0 THEN  1 else 0 END )
              ELSE
              (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
                   END )
    else 0 end )as "bktCount-6",
    SUM(
    CASE WHEN TOTSANCLIMIT  >  200000000
    then
    (Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ELSE 0 end) AS"Bkt_6",
    --total
    sum(
         (Case when  hrk in (13,14) THEN
                     (CASE WHEN bal4 !=0 THEN  1 else 0 END )
                  ELSE
                     (CASE WHEN BAL1-(BAL4-BAL5)!=0 THEN 1 ELSE 0 END)
           end)
    )as "TotCount-7",
    SUM((Case when  hrk in (13,14) THEN 
              to_number(to_char(bal4,'99999999999.99'))
         else
              to_char(BAL1,'99999999999.99')-(to_char(BAL4,'99999999999.99')-to_char(BAL5,'99999999999.99'))
         END )
    ) AS"Total"
    from
    select
    q1.lbrcode,q1.prdacctid,q1.totsanclimit,q2.balance1,balance3,balance4,balance5,balance6,balance7,q3.hrk
    FROM
    SELECT LBRCODE,PRDACCTID,SANCDATE,TOTSANCLIMIT,RNK FROM
               SELECT
               LBRCODE,
               PRDACCTID,
               EFFFROMDATE,
               CURCD,
               PLRLINKYN,
               SANCAUTHORITY,
               SANCDATE,
               TOTSANCLIMIT,
               RANK() OVER (PARTITION BY LBRCODE,PRDACCTID ORDER BY EFFFROMDATE DESC) AS RNK
               FROM LIMIT_MAST
               WHERE LBRCODE IN (3)
    --    AND PRDACCTID LIKE 'PLLN %'
    WHERE RNK=1
    )Q1,
    (SELECT LBRCODE,PRDACCTID,CBLDATE,BALANCE1,BALANCE2,BALANCE3,BALANCE4,BALANCE5,BALANCE6,BALANCE7 FROM
    ( SELECT TRN_MAST.*,
      RANK() OVER(PARTITION BY LBRCODE,PRDACCTID ORDER BY CBLDATE DESC) AS HRK
      FROM TRN_MAST
      WHERE CBLDATE <= TO_DATE('31-MAR-2008','DD-MON-RR')
      AND (LBRCODE,TRIM(SUBSTR(PRDACCTID,1,8))) IN (SELECT LBRCODE,TRIM(PRDCD) FROM PRD_MAST
            WHERE MODULETYPE IN (13,14,30))
    )WHERE HRK=1
    )Q2,
    ( SELECT LBRCODE,TRIM(PRDCD) prd,MODULETYPE hrk FROM PRD_MAST
    WHERE (LBRCODE,TRIM(PRDCD)) IN
    (SELECT LBRCODE,TRIM(SUBSTR(PRDACCTID,1,8)) FROM LIMIT_MAST)
    )q3
    WHERE Q1.LBRCODE=Q2.LBRCODE
    AND Q1.PRDACCTID=Q2.PRDACCTID
    AND TRIM(SUBSTR(Q2.PRDACCTID,1,8))=q3.PRD
    AND Q1.LBRCODE=q3.LBRCODE
    group by lbrcode,trim(substr(prdacctid,1,8))
    order by lbrcode
    /

    Like this?
    SQL> select 123456 my_num from dual;
        MY_NUM
        123456
    SQL>
    SQL> column my_num format 999999.99
    SQL>
    SQL> select 123456 my_num from dual;
        MY_NUM
    123456.00
    SQL>Asif Momen
    http://momendba.blogspot.com

  • Using key word ALL for sub-query

    I don't quite understand the ALL funciton.
    Would anyone please explain it.
    select e.empno, e.ename, e.job, e.salary from employee e
    where e.salary > ALL (select x.salary from employee x
    where x.job = 'Engineer');

    >
    Example:
    select e.empno, e.ename, e.job, e.salary from employee e
    where e.salary > ALL (select x.salary from employee x
    where x.job = 'Engineer');
    Let´s assume that the subquery have this values: 1000, 2000, 3000, 4000.
    then the result will be the people whose salary is bigger than 1000, 2000 3000 and 4000.
    Got it ?Not quite - why not use as your subquery - > (SELECT MAX(x.salary) from employee x where x.job = 'Engineer')?
    Paul...
    Edited by: Paulie on 08-May-2012 23:41

  • Join with another table in pre-query

    Hi,
    We have a large data block and we need to order some columns based on street name for example, not id. The base table of db block contains an id_street column, and 'streets' table contains id and name.
    Ok, in pre-query trigger of that block, we have a complex logic and we dynamically build the where clause. At the end, we set the order_By clause of the block, to order the rows, for example we need to order by the 'my_date' column asc (it's a date type column), and street desc; but street NAME, not id. We don't want to use a from clause query, because the dynamically where clause logic it's complex.
    How can we join the db block table with 'streets' table in pre-query, so when constructing the order by clause to specify something like
    set_block_property('ADRESE_NEZONATE', order_by, 'my_date, name desc');where 'name' is the name of the street, from the 'streets' table.
    Is it possible in pre-query, somehow? Or, in my case where can I join with that table and use that column in pre-query at setting order by?
    Thanks!
    Edited by: Roger25 on 26.04.2013 12:31

    I understand what you say but partially.. please explain in more detail how to do that;
    How should look the adrese_nezonate block, then? I have to add a 'name' column and set copy value from item property to 'STREETS.NAME', and database_property No?
    Then the post-query trigger how should look like (the order by clause)? The post-query sends the entire query (with where/order by clauses) to the server, but in that "select... where... order by" (built dynamically) there are only columns from that block (adrese_nezonate). I need to join with streets, INSIDE that query.
    Thanks.

  • Coupling  INNER  JOIN   with   FOR  ALL  ENTRIES  statement

    Hi  All,
         I   am  coupling   INNER  JOIN  with  FOR  ALL  ENTRIES  statement  .....
         Would   you  please  highlight  its  implications ??   Is  it  a  best  practise ? 
         Is  it  advicable  to  use  MULTIPLE   INNER  JOINs  with  a  FOR  ALL  ENTRIES ???
        SORT itab BY matnr.
        IF NOT itab[] IS INITIAL.
          SELECT       epmatnr epebeln ep~ebelp
                       epwerks epmenge ep~netpr
                       ekps_psp_pnr ebbelnr eb~menge
                       INTO TABLE iekpo
                       FROM ekpo AS ep
                       INNER JOIN ekkn AS ek
                       ON  ekebeln = epebeln
                       AND ekebelp = epebelp
                       INNER JOIN ekbe AS eb
                       ON     ebebeln = epebeln
                       AND    ebebelp = epebelp
                       AND    eb~bwart = '101'
                       FOR ALL  ENTRIES IN itab
                       WHERE   ep~matnr = itab-matnr.
          IF sy-subrc EQ 0.
            SORT iekpo BY matnr werks.
            LOOP  AT  itab ASSIGNING  <itab>.
              READ TABLE iekpo WITH KEY matnr = <itab>-matnr
                                        werks = <itab>-werks
                                        BINARY SEARCH.
              IF sy-subrc EQ 0.
                MOVE iekpo-matnr      TO   itab1-matnr.
                MOVE iekpo-ebeln      TO   itab1-ebeln.
                MOVE iekpo-ebelp      TO   itab1-ebelp.
                MOVE iekpo-netpr      TO   itab1-poprice.
                MOVE iekpo-werks      TO   itab1-werks.
                MOVE iekpo-menge      TO   itab1-menge1.
                MOVE iekpo-menge1     TO   itab1-menge2.
                MOVE iekpo-belnr      TO   itab1-belnr.
                MOVE iekpo-ps_psp_pnr TO   itab1-pspel.
                MOVE <itab>-pspel     TO   itab1-tpspel.
                MOVE <itab>-sobkz     TO   itab1-sobkz.
                MOVE <itab>-fo_qty    TO   itab1-fo_qty.
                MOVE <itab>-schgt     TO   itab1-schgt.
                MOVE <itab>-postp     TO   itab1-postp.
                MOVE <itab>-beskz     TO   itab1-beskz.
                pend_qty = iekpo-menge1 - iekpo-menge2.
                MOVE pend_qty         TO   itab1-pending.
                APPEND itab1.
                pend_qty = 0.
              ENDIF.
            ENDLOOP.
          ENDIF.
        ENDIF.
      ENDIF.
    Regards
    Jaman
    Edited by: ABAP Techie on Sep 15, 2008 12:39 PM
    Edited by: ABAP Techie on Sep 15, 2008 12:41 PM

    best practise ... don't know ... it is allowed and o.k.
    If possible you should of coourse to have no FOR ALL ENTRIES at all !
    Joins, there is no general rule, check indexes etc.
    The first SORT, I don't that it help for anything, use it together with the delete adjacent duplicates if you expect duplicates in the driver table.
    o.k., it can help, if there is a loop afterwards and an append inside, because the new table itab1 is then sorted.
    Siegfried

  • Help on Converting inerr query to sub query

    Hi Guys,
    This query is written in inner join, can any one try to write using sub query.
    SELECT B.CNO
    FROM CUSTEN A
    INNER JOIN ORDS B
    ON A.CNO = B.CNO
    AND A.PRNO = B.PRNO
    INNER JOIN ORDI C
    ON B.ORDNO = C.ORDNO
    INNER JOIN PRD D
    ON C.PRNO = D.PRNO
    WHERE B.STS = 'COM'
    AND B.LMD >= A.LMD
    GROUP BY B.CSTNO, C.PRNO
    HAVING COUNT(B.ORDNO) > 1
    Thanks in advance!
    Regards,
    LKRao
    Edited by: kolipaka on Sep 18, 2012 6:37 PM
    Edited by: kolipaka on Sep 18, 2012 6:38 PM

    Hi,
    kolipaka wrote:
    Hi Guys,
    This query is written in inner join, can any one try to write using sub query. Why?
    We don't know your requirements, so we can't be sure if any solution we might think of meets your requirements.
    ... GROUP BY B.CSTNO, C.PRNOIf you really need to GROUP BY columns from different tables, then you almost certainly want to join those tables. You might be able to get the results you want with a scalar sub-query instead of a join, but that's needlessly complicated.
    You said that what you posted is just a sub-query of some other query. Perhaps the solution involves making changes in that query, too. Post the complete query, CREATE TABLE and INSERT statments for a little sample data, the results you want from that data, and an explanation of how you get those results from that data. Say which columns are unique (expecially the columns used in the join conditions); that could be important.

  • [8i] Need help with hierarchical (connect by) query

    First, I'm working in 8i.
    My problem is, I keep getting the error ORA-01437: cannot have join with CONNECT BY.
    And, the reason I get that error is because one of the criteria I need to use to prune some branches with is in another table... Is there anyway to work around this? I tried an in-line view (but got the same error). I thought about using the connect by query as an in-line view and filtering off what I don't want that way, but I'm not sure how to filter out an entire branch...
    Here is some simplified sample data:
    CREATE TABLE     bom_test
    (     parent          CHAR(25)
    ,     component     CHAR(25)
    ,     qty_per          NUMBER(9,5)
    INSERT INTO     bom_test
    VALUES     ('ABC-1','101-34',10);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','A-109-347',2);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','ABC-100G',1);
    INSERT INTO     bom_test
    VALUES     ('ABC-1','1A247G01',2);
    INSERT INTO     bom_test
    VALUES     ('ABC-100G','70052',18);
    INSERT INTO     bom_test
    VALUES     ('ABC-100G','M9532-278',5);
    INSERT INTO     bom_test
    VALUES     ('1A247G01','X525-101',2);
    INSERT INTO     bom_test
    VALUES     ('1A247G01','1062-324',2);
    INSERT INTO     bom_test
    VALUES     ('X525-101','R245-9010',2);
    CREATE TABLE     part_test
    (     part_nbr     CHAR(25)
    ,     part_type     CHAR(1)
    INSERT INTO     part_test
    VALUES     ('ABC-1','M');
    INSERT INTO     part_test
    VALUES     ('101-34','P');
    INSERT INTO     part_test
    VALUES     ('A-109-347','P');
    INSERT INTO     part_test
    VALUES     ('ABC-100G','M');
    INSERT INTO     part_test
    VALUES     ('1A247G01','P');
    INSERT INTO     part_test
    VALUES     ('70052','P');
    INSERT INTO     part_test
    VALUES     ('M9532-278','P');
    INSERT INTO     part_test
    VALUES     ('X525-101','M');
    INSERT INTO     part_test
    VALUES     ('1062-324','P');
    INSERT INTO     part_test
    VALUES     ('R245-9010','P');This is the basic query (with no pruning of branches):
    SELECT     LEVEL
    ,     b.component
    ,     b.parent
    ,     b.qty_per
    FROM     bom_test b
    START WITH          b.parent     = 'ABC-1'
    CONNECT BY PRIOR     b.component     = b.parentThe query above gives the results:
          LEVEL COMPONENT                 PARENT                        QTY_PER
          1.000 101-34                    ABC-1                          10.000
          1.000 A-109-347                 ABC-1                           2.000
          1.000 ABC-100G                  ABC-1                           1.000
          2.000 70052                     ABC-100G                       18.000
          2.000 M9532-278                 ABC-100G                        5.000
          1.000 1A247G01                  ABC-1                           2.000
          2.000 X525-101                  1A247G01                        2.000
          3.000 R245-9010                 X525-101                        2.000
          2.000 1062-324                  1A247G01                        2.000
    9 rows selected....but I only want the branches (children, grandchildren, etc.) of part type 'M'.
    e.g.:
          LEVEL COMPONENT                 PARENT                        QTY_PER
          1.000 101-34                    ABC-1                          10.000
          1.000 A-109-347                 ABC-1                           2.000
          1.000 ABC-100G                  ABC-1                           1.000
          2.000 70052                     ABC-100G                       18.000
          2.000 M9532-278                 ABC-100G                        5.000
          1.000 1A247G01                  ABC-1                           2.000Any suggestions?

    Hi,
    user11033437 wrote:
    First, I'm working in 8i.
    My problem is, I keep getting the error ORA-01437: cannot have join with CONNECT BY.
    And, the reason I get that error is because one of the criteria I need to use to prune some branches with is in another table... Is there anyway to work around this? I tried an in-line view (but got the same error). Post your query. It's very hard to tell what you're doing wrong if we don't know what you're doing.
    ...but I only want the branches (children, grandchildren, etc.) of part type 'M'.
    e.g.:
    LEVEL COMPONENT                 PARENT                        QTY_PER
    1.000 101-34                    ABC-1                          10.000
    1.000 A-109-347                 ABC-1                           2.000
    1.000 ABC-100G                  ABC-1                           1.000
    2.000 70052                     ABC-100G                       18.000
    2.000 M9532-278                 ABC-100G                        5.000
    1.000 1A247G01                  ABC-1                           2.000
    You mean you want don't want the descendants (children, grandchildren, etc.) of any component whose part_type is not 'M'.
    The part_type of the component itself doesn't matter: component '101-34' is included, even though its part_type is 'P', and component 'X525-101' is excluded, even though its part_type is 'M'.
    >
    Any suggestions?Sorry, I don't have an Oracle 8.1 database at hand now. All three of the queries below get the correct results in Oracle 10.2, and I don't believe they do anything that isn't allowed in 8.1.
    You can't do a join and CONNECT BY in the same query on Oracle 8.1.
    I believe you can do one first, then the other, using in-line views. The frist two queries do the join first.
    --     Query 1: Join First
    SELECT     LEVEL
    ,     component
    ,     parent
    ,     qty_per
    FROM     (     -- Begin in-line view to join bom_test and part_test
              SELECT     b.component
              ,     b.parent
              ,     b.qty_per
              ,     p.part_type     AS parent_type
              FROM     bom_test     b
              ,     part_test     p
              WHERE     p.part_nbr     = b.parent
         )     -- End in-line view to join bom_test and part_test
    START WITH     parent     = 'ABC-1'
    CONNECT BY     parent          = PRIOR component
         AND     parent_type     = 'M'
    ;Query 2 is very much like Query 1, but it does more filtering in the sub-query, returning only rows hose part_type or whose parent's part_type is 'M". Your desired result set will be a tree taken entirely from this set. Query 2 may be faster, because the sub-query is more selective, but then again, it may be slower because it has to do an extra join.
    {code}
    -- Query 2: Join first, prune in sub-query
    SELECT     LEVEL
    ,     component
    ,     parent
    ,     qty_per
    FROM     (     -- Begin in-line view to join bom_test and part_test
              SELECT     b.component
              ,     b.parent
              ,     b.qty_per
              ,     p.part_type     AS parent_type
              FROM     bom_test     b
              ,     part_test     p
              ,     part_test     c
              WHERE     p.part_nbr     = b.parent
              AND     c.part_nbr     = b.component
              AND     'M'          IN (c.part_type, p.part_type)
         )     -- End in-line view to join bom_test and part_test
    START WITH     parent     = 'ABC-1'
    CONNECT BY     parent          = PRIOR component
         AND     parent_type     = 'M'
    {code}
    Query 3, below, takes a completely different approach. It does the CONNECT BY query first, then does a join to see what the parent's part_type is. We can easily cut out all the nodes whose parent's part_type is not 'M', but that will leave components like 'R245-9010' whose parent has part_type 'M', but should be excluded because its parent is excluded. To get the correct results, we can do another CONNECT BY query, using the same START WITH and CONNECT BY conditions, but this time only looking at the pruhed results of the first CONNECT BY query.
    {code}
    --     Query 3: CONNECT BY, Prune, CONNECT BY again
    SELECT     LEVEL
    ,     component
    ,     parent
    ,     qty_per
    FROM     (     -- Begin in-line view of 'M' parts in hierarchy
              SELECT     h.component
              ,     h.parent
              ,     h.qty_per
              FROM     (     -- Begin in-line view h, hierarchy from bom_test
                        SELECT     component
                        ,     parent
                        ,     qty_per
                        FROM     bom_test
                        START WITH     parent     = 'ABC-1'
                        CONNECT BY     parent     = PRIOR component
                   ) h     -- End in-line view h, hierarchy from bom_test
              ,     part_test     p
              WHERE     p.part_nbr     = h.parent
              AND     p.part_type     = 'M'
         )     -- End in-line view of 'M' parts in hierarchy
    START WITH     parent     = 'ABC-1'
    CONNECT BY     parent     = PRIOR component
    {code}
    I suspect that Query 3 will be slower than the others, but if the CONNECT BY query is extremely selective, it may be better.
    It would be interesting to see your findings using the full tables. Please post your observations and the explain plan output.
    As usual, your message is a model of completeness and clarity:
    <ul>
    <li>good sample data,
    <li> posted in a way people can use it,
    <li>clear results,
    <li> good explanation
    <li> nciely formatted code
    </ul>
    Keep up the good work!

Maybe you are looking for

  • What is the max hard drive size in an early 2008 MacBook?

    I've got an early 2008 black macbook.  I want to upgrade from a 250gb hard drive to either a 750gb 7200rpm drive or a 1tb 5200rpm drive.  Will either of these work in there?  I don't know if there is a maximum hard drive size/rpm that I can put in th

  • Magic Mouse changes the values in dialog boxes

    When working in Photoshop and saving files, I noticed that a sideways swipe on the Magic Mouse will change the values in dialog boxes. Unfortunately, it's a little too sensitive. When saving as JPEG and reaching for the keyboard to hit Return for OK,

  • Bank not display in help list

    Hi Guru, I have been created  sixteen bank (A...........P) in FI module and which are displaying in HCM through info type 9 BANK DETAIL. My question is how I block bank (L & K) in the list of bank key of info type 9 in HCM module. The bank L & K Will

  • Undeploying BPEL Process with ant

    Hello, I am trying to undeploy BPEL Process with the ANT Script. I did not wrote it by myself but got it as a sample from http://blogs.oracle.com/rammenon/2007/11/26/#a74 with the admintasks.jar as well. Unfortunately, when I try to undeploy , I reci

  • Business catalyst premium partner program

    Has the Business catalyst premium partner membership been changed, I can't find any references to it anymore. If so what changes have been made? and how do they affect normal members?