Hierarchical query with multiple roots

Hi,
I'm trying to write a sql query to find blocking lock in database. The idea is to get the blocker in 1st column, comma separated list of waiters in 2nd column and number of waiters in 3rd column.
As of now i use below query to get a tree structure
WITH lk AS
     (SELECT  blocking_session||' (Inst-'||blocking_instance || ')' blocker,
             SID||' (Inst-'||inst_id || ')' waiter
        FROM gv$session
       WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
SELECT     LPAD (' ', 2 * (LEVEL - 1)) || waiter lock_tree
      FROM (SELECT *
              FROM lk
            UNION ALL
            SELECT DISTINCT 'root', blocker
                       FROM lk
                      WHERE blocker NOT IN (SELECT waiter
                                              FROM lk))
CONNECT BY PRIOR waiter = blocker
START WITH blocker = 'root';
Result:-
===========
LOCK_TREE
1966 (Inst-1)
  908 (Inst-1)
  1906 (Inst-1)
  1900 (Inst-1)
981 (Inst-1)
  921 (Inst-1)
  937 (Inst-1)
  962 (Inst-1)
  1889 (Inst-1)
  1904 (Inst-1)
  974 (Inst-1) But what i expect is like below. My below query works when there is only one root blocker, but fails when there are multiple root node.
WITH lk AS
     (SELECT blocking_session || '(Inst-' || blocking_instance || ')' blocker,
             SID || '(Inst-' || inst_id || ')' waiter
        FROM gv$session
       WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
SELECT     blocker, SUBSTR (SYS_CONNECT_BY_PATH (waiter, ';'), 2) waiters
      FROM (SELECT   blocker, waiter, ROW_NUMBER () OVER (ORDER BY waiter)
                                                                          val
                FROM lk
            GROUP BY blocker, waiter)
     WHERE CONNECT_BY_ISLEAF = 1
START WITH val = 1
CONNECT BY PRIOR val = val - 1
Result:-
===========
  WAITERS# BLOCKER                                                                                 WAITERS
         3 981(Inst-1)                                                                             1904(Inst-1);921(Inst-1);937(Inst-1)
....lot of duplicates
expected result:-
===========
  WAITERS# BLOCKER                                                                                 WAITERS
         4 981(Inst-1)                                                                             1904(Inst-1);921(Inst-1);937(Inst-1);974(Inst-1)
         3 1966(Inst-1)                                                                             908 (Inst-1);1906 (Inst-1);1900 (Inst-1) can you please help me correct above query or suggest other ways to archive this result.
Thanks in advance
MidhunGT

Hi All,
Thank you all for your support. I never knew these many ways to see blocking lock in database :)
Somehow i was able get the desired result for my specific requirement with below query
sql> WITH lk AS
  2       (SELECT blocking_session || ' (Inst-' || blocking_instance
  3               || ')' blocker,
  4               SID || ' (Inst-' || inst_id || ')' waiter
  5          FROM gv$session
  6         WHERE blocking_instance IS NOT NULL AND blocking_session IS NOT NULL)
  7  SELECT     blocker,
  8             LTRIM
  9                (MAX (SYS_CONNECT_BY_PATH (waiter, ','))KEEP (DENSE_RANK LAST ORDER BY cnt),
10                 ','
11                ) AS waiters,
12             MAX (cnt) waiters#
13        FROM (SELECT blocker, waiter,
14                     ROW_NUMBER () OVER (PARTITION BY blocker ORDER BY waiter)
15                                                                         AS cnt
16                FROM lk)
17    GROUP BY blocker
18  CONNECT BY cnt - 1 = PRIOR cnt AND blocker = PRIOR blocker
19  START WITH cnt = 1;
BLOCKER         WAITERS                                                                            WAITERS#
1946 (Inst-1)   1987 (Inst-1),879 (Inst-1),910 (Inst-1)                                                3
930 (Inst-1)    1919 (Inst-1),1945 (Inst-1),1953 (Inst-1),1983 (Inst-1)                                4please advice, if any scope for improvement
Thanks and Regards,
MidhunGT

Similar Messages

  • RegionRenderer encodeAll The region component with id: pt1:r1 has detected a page fragment with multiple root components. Fragments with more than one root component may not display correctly in a region and may have a negative impact on performance.

    Hi,
    I am using JDEV 11.1.2.1.0
    I am getting the following error :-
    <RegionRenderer> <encodeAll> The region component with id: pt1:r1 has detected a page fragment with multiple root components. Fragments with more than one root component may not display correctly in a region and may have a negative impact on performance. It is recommended that you restructure the page fragment to have a single root component.
    Piece of code is for region is:-
       <f:facet name="second">
                                                <af:panelStretchLayout id="pa1"
                                                                       binding="#{backingBeanScope.Assign.pa1}">
                                                    <f:facet name="center">
                                                        <af:region value="#{bindings.tfdAssignGraph1.regionModel}" id="r1"
                                                                   binding="#{backingBeanScope.Assign.r1}"/>
                                                    </f:facet>
                                                </af:panelStretchLayout>
                                            </f:facet>
    How do I resolve it ?
    Thanks,

    Hi,
    I see at least 3 errors
    1. <RegionRenderer> <encodeAll> The region component with id: pt1:r1 has detected a page fragment with multiple root components.
    the page fragment should only have a single component under the jsp:root tag. If you see more than one, wrap them in e.g. an af:panelGroupLayout or af:group component
    2. SAPFunction.jspx/.xml" has an invalid character ".".
    check the document (you can open it in JDeveloper if the customization was a seeded one. Seems that editing this file smething has gone bad
    3. The expression "#{bindings..regionModel}" (that was specified for the RegionModel "value" attribute of the region component with id "pePanel") evaluated to null.
    "pageeditorpanel" does seem to be missing in the PageDef file of the page holding the region
    Frank

  • MDS Customization Problem with multiple root components

    Hello,
    Oracle JDeveloper 11.1.1.5.0 and WebLogic Server Version: 10.3.5.0
    I am using Oracle MDS Customization class with the following classes:
    oracle.adf.view.rich.change.MDSDocumentChangeManager
    org.apache.myfaces.trinidad.change.ChangeManager
    org.apache.myfaces.trinidad.change.MoveChildComponentChange
    Based on these classes I am moving UI components
    <af:panelStretchLayout>
    <f:facet name="center">
    <af:region />
    </f:facet>
    </af:panelStretchLayout>
    into another component thanks to the MDS.
    Once I do the movement and persist, I receive the following waning message:
    *<RegionRenderer> <encodeAll> The region component with id: pt1:r1:0:pt2:r1:0:r1 has detected a page fragment with multiple root components. Fragments with more than one root component may not display correctly in a region and may have a negative impact on performance. It is recommended that you restructure the page fragment to have a single root component.*
    When I run the application in Oracle JDeveloper 11.1.1.5.0, it work fine, but when I deploy it on WebLogic Server Version: 10.3.5.0 it is not working.
    I receive the same warning message on the server and in JDeveloper.
    I think that MDS makes a copy of the components that I move because of that it says me that "a page fragment with multiple root components"
    The problem is not because of duplication any of the tags <af:document> <f:view><f:form> <html> <head> <body>
    After the movement and persistence, I also call the FacesContext to reset its view root with the following code:
    FacesContext context =FacesContext.getCurrentInstance();
    String currentView = context.getViewRoot().getViewId();
    ViewHandler vh = context.getApplication().getViewHandler();
    UIViewRoot x = vh.createView(context, currentView);
    x.setViewId(currentView);
    context.setViewRoot(x);
    The idea is that the entire JSF tree to be rebuild on entering page with aim to clear previously drag and drop settings.
    Do you know how I can overcome the problem on the server WebLogic Server Version: 10.3.5.0?
    This worked on Oracle JDeveloper 11.1.1.3.0 and now the problem is with Oracle JDeveloper 11.1.1.5.0.
    Regards,
    Niki

    Hi,
    what the error means is that you have more than one node under the jsp:root node of the fragment. Say the content of your fragment is
    <af:panelGroupLayout id="pgl1">
    </af:PanelGrouPLayout>
    Then this is okay
    if you have
    <af:panelGroupLayout id="pgl1">
    </af:PanelGrouPLayout>
    <af:panelGroupLayout id="pgl2">
    </af:PanelGrouPLayout>
    or
    <af:panelGroupLayout id="pgl1">
    </af:PanelGrouPLayout>
    <af:commandButton id="cb1"/>
    Then these mean duplicated root components. The JDeveloper IDE flags this as Warnings (Structure Window) when selecting the page fragment
    Frank

  • "detected a page fragment with multiple root components" warning

    I am getting a warning on the standalone WLS when I run my page that contains a taskflow as region. I am using a page fragment in my taskflow.
    <Warning> <oracle.adfinternal.view.faces.renderkit.rich.RegionRenderer> <ADF_FACES-60099> <The region component with id: ptMain:r1 has detected a page fragment with multiple root components. Fragments with more than one root component may not display correctly in a region and may have a negative impact on performance. It is recommended that you restructure the page fragment to have a single root component.>
    The warning states the obvious, I have everything within a panelheader in my page fragment. Also, I do not get the warning on the integrated WLS. Any ideas as to why this warning is still popping up in the log? I am using JDev 11.1.1.3.
    Thanks,
    Jessica

    Thank you for responding. I do not have any popups. I do, however, have another region nested within this fragment ( have this warning on another fragment that doesn't have a nested region though). Here is the code for my fragment.
    <?xml version='1.0' encoding='UTF-8'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich"
    xmlns:f="http://java.sun.com/jsf/core">
    <af:panelHeader text="Pawn"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.ph1}"
    id="ph1" type="default">
    <af:panelFormLayout id="pfl2">
    <af:panelSplitter binding="#{backingBeanScope.backing_Fragments_PawnSearch.ps1}"
    id="ps1" orientation="vertical" splitterPosition="62"
    inlineStyle="width:775px; height:660px;">
    <f:facet name="first">
    <af:panelBox text="Search #{bindings.agency.inputValue} Data to Update"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.pb1}"
    id="pb1">
    <f:facet name="toolbar"/>
    <af:panelGroupLayout id="pgl3" layout="horizontal">
    <af:inputText value="#{bindings.control_number.inputValue}"
    label="Control Number" required="true"
    columns="#{bindings.control_number.hints.displayWidth}"
    maximumLength="#{bindings.control_number.hints.precision}"
    shortDesc="#{bindings.control_number.hints.tooltip}"
    id="it1">
    <f:validator binding="#{bindings.control_number.validator}"/>
    </af:inputText>
    <af:inputDate value="#{bindings.trans_date.inputValue}"
    label="Date" required="true"
    shortDesc="#{bindings.trans_date.hints.tooltip}"
    id="id1">
    <f:validator binding="#{bindings.trans_date.validator}"/>
    <af:convertDateTime pattern="#{bindings.trans_date.format}"/>
    </af:inputDate>
    <af:inputText value="#{bindings.agency.inputValue}" simple="true"
    required="#{bindings.agency.hints.mandatory}"
    columns="#{bindings.agency.hints.displayWidth}"
    maximumLength="#{bindings.agency.hints.precision}"
    shortDesc="#{bindings.agency.hints.tooltip}"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.it2}"
    id="it2" visible="false">
    <f:validator binding="#{bindings.agency.validator}"/>
    </af:inputText>
    <af:commandButton actionListener="#{bindings.ExecuteWithParams.execute}"
    text="Search"
    disabled="#{!bindings.ExecuteWithParams.enabled}"
    id="cb5"
    returnListener="#{backingBeanScope.backing_Fragments_PawnSearch.refreshPage}"
    action="#{backingBeanScope.backing_Fragments_PawnSearch.RenderMe}">
    <af:setActionListener from="#{bindings.PawnItemView1Iterator.currentRowKeyString}"
    to="#{requestScope.pawnkey}"/>
    </af:commandButton>
    <af:spacer width="10" height="10"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.s1}"
    id="s1"/>
    <af:goButton text="Clear Values and Create New" id="gb1"
    destination="index.jspx"
    rendered="#{backingBeanScope.backing_Fragments_PawnSearch.saveButtonRendered}"/>
    </af:panelGroupLayout>
    </af:panelBox>
    </f:facet>
    <f:facet name="second">
    <af:panelGroupLayout binding="#{backingBeanScope.backing_Fragments_PawnSearch.pgl4}"
    id="pgl4" layout="scroll" partialTriggers=""
    visible="true">
    <af:panelGroupLayout binding="#{backingBeanScope.backing_Fragments_PawnSearch.pgl6}"
    id="pgl6" inlineStyle="width:775px;"
    visible="#{backingBeanScope.backing_Fragments_PawnSearch.renderTF}">
    <af:region value="#{bindings.PawnEntryFormTF1.regionModel}"
    id="r1" inlineStyle="width:750px;"/>
    </af:panelGroupLayout>
    <af:panelGroupLayout binding="#{backingBeanScope.backing_Fragments_PawnSearch.pgl5}"
    id="pgl5" layout="horizontal"
    visible="#{backingBeanScope.backing_Fragments_PawnSearch.renderMessage}">
    <af:outputFormatted value="No #{bindings.agency.inputValue} Pawn data matching the Control Number and Transaction Date from above."
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.of1}"
    id="of1"
    inlineStyle="font-weight:bolder; font-size:small;"/>
    <af:spacer width="10" height="10"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.s2}"
    id="s2"/>
    <af:goButton text="Clear Search and Start Again"
    binding="#{backingBeanScope.backing_Fragments_PawnSearch.gb2}"
    id="gb2" destination="index.jspx"/>
    </af:panelGroupLayout>
    </af:panelGroupLayout>
    </f:facet>
    </af:panelSplitter>
    </af:panelFormLayout>
    </af:panelHeader>
    <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_Fragments_PawnSearch-->
    </jsp:root>

  • Doubt in Firing Query with multiple opportunities UUID/IDs

    HI Folks!
    I might have simple doubt but please help me on this!
    1. I have a custom BO with association to opportunities.
    [DeploymentUnit(CustomerRelationshipManagement)] businessobject Sy_Trade {
    [AlternativeKey] [Label("Trade Id")] element tradeid : BusinessTransactionDocumentID;
    node RelatedOpportunities [0,n]{
                                  element BusinessTransactionDocumentReference : BusinessTransactionDocumentReference;
                                  element BusinessTransactionDocumentRelationshipRoleCode : BusinessTransactionDocumentRelationshipRoleCode;
                                   association RelatedOpportunity[0,1] to Opportunity;
    2. I have success fully used association and i am able to view create all the opportunities related to my custom Bo.
    ISSUE : I want a facet where i just want DISPLAY the activities and sales document assigned in the RELATED OPPORTUNITIES ( N opportunities )
    How do i query with Multiple opportunities ID and fetch the activities against it?
    Btw I want to use query in UI Designer... I have created an  advanced list pane and there i want the result list
    I hope i am clear!
    Thanks in adavance...
    Regards
    Dhruvin

    Hi Ludger,
    I have successfully displayed Related Opportunities associated with trade.( i am able to create , delete also )
    Issue : I am not able to "Display" ( i don't need to edit or create ) all the activities created against all the opportunities in a different tab.
    I tried to approaches :
    1: Query : Created a Query on Activity BO and tried to pass multiple related opportunities ( but seems not possible , please tell me any possibility to pass range of opportunity via transformation or anything? )
    2 : binding : I have a Node Related Opportunity so just tried to bind it with BO model but problem is it is displaying all the activities of first opportunity of the list...
    i think why because :
    In Data model I have created a table bind with Related Opportunities...
    now that node is 1 to N , association to opportunity 0 to 1 , hence i think it fetches only 1 opportunities activity
    should i create like below ( Or is it possible)
    Node Reltdoppts[0,1]
    association [0,N] to opportunity BO ?
    Although i strongly feel SAP should provied us two things :
    1. We need to pass range of opportunities in a query.
    2. We need to just write some absl code where i can fill the table and display it
    and also is there any possibility to create a report or something to display activities as we just want to display the activities!
    P.S : I have been getting a lot of bashing from client because some of the product restriction in cloud! i hope and wish SAP give developers free hand to develop right now its like our hands are tied to many things

  • BaseTableName blank when calling GetSchema on a query with multiple tables

    I am using ODP.NET 11.2.0.3.0 and when calling GetSchemaTable on a DataReader that contains a join the returned SchemaTable has the BaseTableName and BaseColumnName fields blank - this is different than what I see with the Oracle OLE DB Provider and with how SQL Server's native provider works. I can't find any discussion of this - is this on purpose or is it a bug? why does the available schema information vary so drastically between a single table query and a query with multiple tables joined?
    Thanks,
    Bryan Hinton

    Hi Bryan,
    I am also facing the same issue. Did u find any work around or any suggestions will be well appreciated.
    Thanks,
    Naresh.

  • Oracle hangs on query with multiple joins

    To test the sotftware from the LMS-vendor that are out partners we use virtual machines where we install Windows 2003 servers and Oracle XE
    While we were testing the software I've found that a particular query with multiple unions causes the CPU of the virtual machine totally claimed by oracle
    The query causes oracle to hang.
    I've found that the subcomponents of the query all return 0 rows (and response all immediately) combined into a query with at least 2 unions the query hangs the system
    I'm not familiar with with Database Management at all
    I've read something about SGA and PGA that could be the issue and tried to increase the target for both but it doesn't seem to do anything
    Some characterics
    Target Current
    Maximum System Global Area (SGA) Size: 380 MB 380 MB
    Program Global Area (PGA) Aggregate Target: 360 MB 38 MB
    Current Configuration: (SGA + PGA): 740 MB 418 MB
    Tablespaces Percent Used Allocated (MB) Used (MB) Datafiles
    SYSAUX 98.21% 460.00 451.75 1
    SYSTEM 73.09% 510.00 372.75 1
    DATA 99.13% 440.00 436.19 1
    UNDO 6.48% 160.00 10.38 1
    USERS 1.63% 100.00 1.63 1
    sort_area_size 65536
    shared_pool_reserved_size 5452595 TRUE size in bytes of reserved area of shared pool
    shared_pool_size 0 TRUE size in bytes of shared pool
    What other parameters are important? How could I get a good picture to see what's really going on?
    Some pointers, help would be appreciated.
    Regards,
    Remco

    Below is the base-query that is causing the problems
    SELECT /* Public - Internal learner */ r.id reg_id, i.id order_item_id, o.id order_id, o.order_no order_number, e.id person_id, format_name(e.fname , e.lname , @@005) learner_name , c.id company_id, c.name2 , ent.id entid, ctype.id ctypeid, ctype.name , i.status , items.description item_desc, substr ( i.flags , 1 , 1 ) is_conf , r.status status1, rs.description description1 , r.wlist_priority , r.reg_no , r.flags , o.status status2, o.split, null learnerViewOnly, null statusViewOnly, i.approved_status, decode(substr(r.flags,2,1),'1','true','false') isWalkIn, oa.id offering_action_id, oa.status profile_status ,c.name2 org_name ,ctype.name audience_sub_type ,items.description description ,o.order_no order_no ,orderList.description order_status ,approvalList.description approval_status ,e.fname learner_first_name ,e.lname learner_last_name FROM tpt_registration r INNER JOIN tpt_oe_order_items i ON i.reg_id = r.id INNER JOIN tpt_oe_order o ON i.order_id = o.id INNER JOIN cmt_person e ON r.student_id = e.id INNER JOIN tpt_company c ON e.company_id = c.id INNER JOIN tpt_offering_action oa on r.offering_action_id = oa.id LEFT OUTER JOIN tpt_roster_template_entry ent ON r.ros_temp_ent_id = ent.id LEFT OUTER JOIN tpt_customer_type ctype ON ent.customer_type_id = ctype.id INNER JOIN fgt_ext_sys_list_of_val rs ON to_char ( r.status ) = rs.name INNER JOIN fgt_ext_sys_list_of_val items ON to_char ( i.status ) = items.name INNER JOIN fgt_ext_sys_list_of_val orderList ON to_char ( o.status ) = orderList.name INNER JOIN fgt_ext_sys_list_of_val approvalList ON to_char(i.approved_status) = approvalList.name WHERE e.type = 100 AND r.class_id = @@001 AND r.status = nvl ( to_number(@@002) , r.status ) AND rs.locale_id = @@005 AND rs.list_id = 'sysli000000000000100' AND items.locale_id = @@005 AND items.list_id = 'sysli000000000000131' AND orderList.list_id = 'sysli000000000000129' AND orderList.locale_id = @@005 AND approvalList.list_id = 'sysli000000000000165' AND approvalList.locale_id = @@005 AND ((@@003 is null) or (@@003 is not null and r.student_id = @@003))
    UNION
    SELECT /* Public - External learner */ r.id reg_id, i.id order_item_id, o.id order_id, o.order_no , e.id person_id, format_name(e.fname , e.lname , @@005) , c.id company_id, c.name2 , ent.id entid, ctype.id ctypeid, ctype.name , i.status , items.description , substr ( i.flags , 1 , 1 ) is_conf , r.status status1, rs.description description1, r.wlist_priority , r.reg_no , r.flags , o.status status2, o.split, null learnerViewOnly, null statusViewOnly, i.approved_status, decode(substr(r.flags,2,1),'1','true','false') isWalkIn, oa.id offering_action_id, oa.status profile_status ,c.name2 org_name ,ctype.name audience_sub_type ,items.description description ,o.order_no order_no ,orderList.description order_status ,approvalList.description approval_status ,e.fname learner_first_name ,e.lname learner_last_name FROM tpt_registration r INNER JOIN tpt_oe_order_items i ON i.reg_id = r.id INNER JOIN tpt_oe_order o ON i.order_id = o.id INNER JOIN cmt_person e ON r.student_id = e.id INNER JOIN tpt_offering_action oa on r.offering_action_id = oa.id LEFT OUTER JOIN tpt_company c ON e.company_id = c.id LEFT OUTER JOIN tpt_roster_template_entry ent ON r.ros_temp_ent_id = ent.id LEFT OUTER JOIN tpt_customer_type ctype ON ent.customer_type_id = ctype.id INNER JOIN fgt_ext_sys_list_of_val rs ON to_char ( r.status ) = rs.name INNER JOIN fgt_ext_sys_list_of_val items ON to_char ( i.status ) = items.name INNER JOIN fgt_ext_sys_list_of_val orderList ON to_char ( o.status ) = orderList.name INNER JOIN fgt_ext_sys_list_of_val approvalList ON to_char(i.approved_status) = approvalList.name WHERE e.type = 200 AND r.class_id = @@001 AND r.status = nvl ( to_number(@@002) , r.status ) AND rs.locale_id = @@005 AND rs.list_id = 'sysli000000000000100' AND items.locale_id = @@005 AND items.list_id = 'sysli000000000000131' AND orderList.list_id = 'sysli000000000000129' AND orderList.locale_id = @@005 AND approvalList.list_id = 'sysli000000000000165' AND approvalList.locale_id = @@005 AND ((@@003 is null) or (@@003 is not null and r.student_id = @@003))
    UNION
    SELECT /* Public - Unassigned learner */ r.id reg_id, i.id order_item_id, o.id order_id, o.order_no , null person_id, null , null company_id, null , ent.id entidd, ctype.id ctypeid, ctype.name , i.status , items.description , substr ( i.flags , 1 , 1 ) is_conf , r.status status1, rs.description description1, r.wlist_priority , r.reg_no , r.flags , o.status status2, o.split, null learnerViewOnly, null statusViewOnly, i.approved_status, decode(substr(r.flags,2,1),'1','true','false') isWalkIn, oa.id offering_action_id, oa.status profile_status ,'' org_name ,ctype.name audience_sub_type ,items.description description ,o.order_no order_no ,orderList.description order_status ,approvalList.description approval_status ,'' learner_first_name ,'' learner_last_name FROM tpt_registration r INNER JOIN tpt_oe_order_items i ON i.reg_id = r.id INNER JOIN tpt_oe_order o ON i.order_id = o.id INNER JOIN tpt_offering_action oa on oa.id = r.offering_action_id LEFT OUTER JOIN tpt_roster_template_entry ent ON r.ros_temp_ent_id = ent.id LEFT OUTER JOIN tpt_customer_type ctype ON ent.customer_type_id = ctype.id INNER JOIN fgt_ext_sys_list_of_val rs ON to_char ( r.status ) = rs.name INNER JOIN fgt_ext_sys_list_of_val items ON to_char ( i.status ) = items.name INNER JOIN fgt_ext_sys_list_of_val orderList ON to_char ( o.status ) = orderList.name INNER JOIN fgt_ext_sys_list_of_val approvalList ON to_char(i.approved_status) = approvalList.name WHERE r.class_id = @@001 AND r.status = nvl ( to_number(@@002) , r.status ) AND r.student_id is null AND rs.locale_id = @@005 AND rs.list_id = 'sysli000000000000100' AND items.locale_id = @@005 AND items.list_id = 'sysli000000000000131' AND orderList.list_id = 'sysli000000000000129' AND orderList.locale_id = @@005 AND approvalList.list_id = 'sysli000000000000165' AND approvalList.locale_id = @@005 AND @@003 is null
    UNION
    SELECT /* Private - Internal learner */ r.id reg_id, i.id order_item_id, o.id order_id, o.order_no , e.id person_id, format_name(e.fname , e.lname , @@005) , c.id company_id, c.name2 , ent.id entid, ctype.id ctypeid, ctype.name , i.status , items.description , substr ( i.flags , 1 , 1 ) is_conf , r.status status1, rs.description description1 , r.wlist_priority , r.reg_no , r.flags , o.status status2, o.split, null learnerViewOnly, null statusViewOnly, i.approved_status, decode(substr(r.flags,2,1),'1','true','false') isWalkIn, oa.id offering_action_id, oa.status profile_status ,c.name2 org_name ,ctype.name audience_sub_type ,items.description description ,o.order_no order_no ,orderList.description order_status ,approvalList.description approval_status ,e.fname learner_first_name ,e.lname learner_last_name FROM tpt_registration r INNER JOIN let_pvt_offering_request pvt_offreq ON pvt_offreq.class_id = r.class_id INNER JOIN tpt_offering_action oa on oa.id = r.offering_action_id LEFT OUTER JOIN tpt_oe_order_items i ON i.part_id = pvt_offreq.id LEFT OUTER JOIN tpt_oe_order o ON i.order_id = o.id INNER JOIN cmt_person e ON r.student_id = e.id LEFT OUTER JOIN tpt_company c ON e.company_id = c.id LEFT OUTER JOIN tpt_roster_template_entry ent ON r.ros_temp_ent_id = ent.id LEFT OUTER JOIN tpt_customer_type ctype ON ent.customer_type_id = ctype.id INNER JOIN fgt_ext_sys_list_of_val rs ON to_char ( r.status ) = rs.name LEFT OUTER JOIN fgt_ext_sys_list_of_val items ON to_char ( i.status ) = items.name AND items.locale_id = @@005 AND items.list_id = 'sysli000000000000131' LEFT OUTER JOIN fgt_ext_sys_list_of_val orderList ON to_char ( o.status ) = orderList.name AND orderList.list_id = 'sysli000000000000129' AND orderList.locale_id = @@005 LEFT OUTER JOIN fgt_ext_sys_list_of_val approvalList ON to_char(i.approved_status) = approvalList.name AND approvalList.list_id = 'sysli000000000000165' AND approvalList.locale_id = @@005 WHERE e.type = 100 AND r.class_id = @@001 AND r.status = nvl ( to_number(@@002) , r.status ) AND rs.locale_id = @@005 AND rs.list_id = 'sysli000000000000100' AND ((@@003 is null) or (@@003 is not null and r.student_id = @@003))
    UNION
    SELECT /* Private - External learner */ r.id reg_id, i.id order_item_id, o.id order_id, o.order_no , e.id person_id, format_name(e.fname , e.lname , @@005) , c.id company_id, c.name2 , ent.id entid, ctype.id ctypeid, ctype.name , i.status , items.description , substr ( i.flags , 1 , 1 ) is_conf , r.status status1, rs.description description1 , r.wlist_priority , r.reg_no , r.flags , o.status status2, o.split, null learnerViewOnly, null statusViewOnly, i.approved_status, decode(substr(r.flags,2,1),'1','true','false') isWalkIn, oa.id offering_action_id, oa.status profile_status ,c.name2 org_name ,ctype.name audience_sub_type ,items.description description ,o.order_no order_no ,orderList.description order_status ,approvalList.description approval_status ,e.fname learner_first_name ,e.lname learner_last_name FROM tpt_registration r INNER JOIN let_pvt_offering_request pvt_offreq ON pvt_offreq.class_id = r.class_id INNER JOIN tpt_offering_action oa on r.offering_action_id = oa.id LEFT OUTER JOIN tpt_oe_order_items i ON i.part_id = pvt_offreq.id LEFT OUTER JOIN tpt_oe_order o ON i.order_id = o.id INNER JOIN cmt_person e ON r.student_id = e.id LEFT OUTER JOIN tpt_company c ON e.company_id = c.id LEFT OUTER JOIN tpt_roster_template_entry ent ON r.ros_temp_ent_id = ent.id LEFT OUTER JOIN tpt_customer_type ctype ON ent.customer_type_id = ctype.id INNER JOIN fgt_ext_sys_list_of_val rs ON to_char ( r.status ) = rs.name LEFT OUTER JOIN fgt_ext_sys_list_of_val items ON to_char ( i.status ) = items.name AND items.locale_id = @@005 AND items.list_id = 'sysli000000000000131' LEFT OUTER JOIN fgt_ext_sys_list_of_val orderList ON to_char ( o.status ) = orderList.name AND orderList.locale_id = @@005 AND orderList.list_id = 'sysli000000000000129' LEFT OUTER JOIN fgt_ext_sys_list_of_val approvalList ON to_char(i.approved_status) = approvalList.name AND approvalList.locale_id = @@005 AND approvalList.list_id = 'sysli000000000000165' WHERE e.type = 200 AND r.class_id = @@001 AND r.status = nvl ( to_number(@@002) , r.status ) AND rs.locale_id = @@005 AND rs.list_id = 'sysli000000000000100' AND ((@@003 is null) or (@@003 is not null and r.student_id = @@003)) ORDER BY 34,35,28,29,31,30,33,32

  • APD using Query with multiple structures as a data source

    All,
    I want to set up an automatic process which executes a query and exports it to a shared drive as a csv file. I have tried various options , when I try to use APD to set up the extract, I get an error and this is because the query that I am trying to use has Strucutres in both rows and columns. Hence, I am unable to use this option. I tried RSCRM_BAPI, It works well, but there is an issue with scheduling this in Process chain. I created an event and scheduled this as a job to trigger after "event" as per SAP instructions, but the job does not exist and it is not possible to trigger it through the Process chain unless the variables are hard coded in the query which I do not want to do.
    Can any one tell me if there is a way to deal with APD using Query with multiple structures?
    Would really appreciate if some one can give me the right solution...
    Thanks

    Hi Tanu ,
    APD is an option but its not very good with large amount of data or hiearachies or if you have attributes in you query structure .
    One more option for this requirement is use of report program using function module RRW3_GET_QUERY_VIEW_DATA .
    This will work fine with multiple structure etc .
    There are some overheads with this FM  ex: if amount of data is too much then program will give dump .Solution for that is we call the FM in LOOP by diving amount of data need to be fetched .ex:  we can read data quarter wise.
    For using this function module what you can do is write an ABAP program (At SE38 ) .which will call this FM and then write the output into a flat file which you can save at application server (AL11) .From there other system can read it .
    To automate this whole process you can further add all the report programs into a process chain (RSPC) which can be schedule as per requirement .
    To pass input parameters you can use variants that will pass the values to the report .
    Check thi link for sample code :
    [http://www.tricktresor.de/content/index.php?navID=696&aID=496]
    Hope this will be helpful .
    Regards,
    Jaya Tiwari

  • Hierarchical query with many-to-many relationship

    I have read with interest the creative solutions to complex hierarchical queries posted previously; they have been instructive but have not quite addressed this scenario.
    We have a hierarchy table H, with columns for ID, name, parentID, and other attributes.
    Within this table are a number of independent hierarchies, each existing for a different purpose.
    We have a master list of hierarchies in table T which describes the purpose of each hierarchy, provides some default attributes which the nodes can inherit, and stores a unique id for each hierarchy and a pointer to the root node of the corresponding hierarchy in table H.
    We have a master list of items M, with identically named columns to those in H, along with many other attributes.
    The members of table M ALL belong to EACH of the Hierarchies. So we have a link table I to define the intersection of H and M.
    So the leaf nodes of H are really containers for the list of elements from M which may be attached to them.
    The universe of M is very volatile, with new members being added, old ones deleted, and existing ones being reclassified frequently from node to node within each hierarchy. Since the hierarchies have to be built to handle every possible scenario, so that the members of M can always find a suitable node to reside in, quite often, in fact more often than not, the majority of leaf nodes for each hierarchy are empty at any given moment.
    Therefore, although we always know the root sector of a given hierarchy and can traverse downwards from there, if we worked our way up from the intersection table, we could eliminate up to 70% of the nodes of any given hierarchy from further consideration, as they don't need to be (in fact, must not be) included in reports.
    As implied by the above, rows in M are structurally similar (in terms of columns, but not in any real world sense) and are a superset of rows in H. But combining them into the one table doesn't seem to help the reporting process due to the many-to-many relationship which prevents the ID/parentID relationship from being carried through to this level.
    There are a number of other considerations of which the most pertinent is that the people using this database generally have an interest in only a subset of the master list of items in M. This relationship is also dynamic but important enough and rigid enough that another link table P exists to combine the Users in table U with the subset of M in which they are interested. (The users are also grouped into hierarchies of a totally different nature, but this aspect is secondary for now.)
    The reporting is reasonably straightforward for any single combination of User and Hierarchy; they want to see all the items they are interested in, listed in hierarchical sequence, totalled on change of level with the individual items M listed beneath the nodes of H. This is unfortunately required in real time, so retrieval performance is paramount.
    Some statistics might help to determine the optimum approach:
    The largest hierarchy has 10,000 nodes. The smallest about 100.
    The largest would have 70% or more of its nodes unused at any point in time, and even the smallest would have 25% unused.
    The hierarchies tend to be broad rather than deep, the maximum number of levels being about 5; but the larger ones should be twice as deep as this if performance was not compromised.
    There are dozens of hierarchies, but it may be possible to sharply reduce this number by exploiting the Order Siblings By clause.
    The number of rows in M varies between 500,000 and 50,000; depending upon how long historical data is retained on-line (and performance permitting, it would be retained indefinitely).
    The number of users varies between 1000 and 2000 but the range of M in which they are interested varies greatly; from as few as 100 to as many as 10,000+. So it is almost always worth beginning by eliminating the items in which they are not interested, implying once again that the hierarchy should be traversed upwards rather than down from the root.
    The current system is very old and survives by a tactic of building what are essentially materialised views of the database structure for each user overnight using, ahem, non-relational technology. This is inefficient and not easily scaled (but it works) and hence this redevelopment project needs to (a) work, and (b) work better and faster.
    I am happy to provide some DDL scripts if that helps explain the problem better than this narrative.
    I can't help feeling that the solution lies in somehow extending the hierarchical query past the many-to-many link table so that the Master list can be merged directly into the hierarchy such that the M items become the leaf nodes rather than the design outlined above - but I don't know how to do that. But I am sure everyone reading this does! :)
    All advice appreciated. Database version is not an issue; we are currently using version 10XE for experimentation, but production usage could be on 11 if that contains helpful features.
    Thank you
    CS

    Hi,
    ChrisS. wrote:
    I am happy to provide some DDL scripts if that helps explain the problem better than this narrative.Yes, please do.
    The problem seems interesting, I'm sure many people here (including myself) are willing to help you in this matter.
    So yes, post DDL for the tables, as well as INSERTs to populate them with representative data. Please also include the output you require along with detailed explanations about the logic to get it.
    Don't forget to put lines of code between &#x007B;code&#x007D; tags in order to preserve formatting and readability, like this :
    SELECT sysdate FROM dual;Thanks.

  • Hierarchical query with out using Connect by prior

    Hi Guys,
    I am supporting a product which is enterprise based and only allowd to write queries which are ANSII standard.
    I have an requirement like If I provide the child I need to know all the parents till  highest level.
    My table structure is like below
    Table_name :  Org_unit
    Columns are
    Org_unit_id name desc  parent_org_unit_id
    I wil pass the org_unit id and want to list all the parents of the chile org_unit_id and it has to be accomplished without  using connec by prior.
    Please suggest me some ideas and aprroches
    I am using Orcle 11g version

    Hi,
    960593 wrote:
    Hi Guys,
    I am supporting a product which is enterprise based and only allowd to write queries which are ANSII standard.
    I have an requirement like If I provide the child I need to know all the parents till  highest level.
    My table structure is like below
    Table_name :  Org_unit
    Columns are
    Org_unit_id name desc  parent_org_unit_id
    I wil pass the org_unit id and want to list all the parents of the chile org_unit_id and it has to be accomplished without  using connec by prior.
    Please suggest me some ideas and aprroches
    I am using Orcle 11g version
    The data model you posted (org_unit_id as primary key, parent_org_unit_id as foreign key to the same table for the parent, when there is a parent) is called the Adjacency Model because it keeps track of which nodes are adjacent (or next to) each other.
    I'm familiar with 2 other ways to model hierarchies: the Nested Sets Model, and what I call the Lineage Model.  I'll show how to find a given node's ancestors (in hierarchical order) in each model.  Neither the Nested Sets nor the Lineage Model requires CONNECT BY or recursive WITH clauses to work.
    The following table contains all the columns necessary for using each of these 3 models:
         EMPNO        MGR ENAME      LINEAGE                    NS_LOW NS_HIGH
          7839            KING       /7839/                          1      28
          7698       7839 BLAKE      /7839/7698/                     2      13
          7499       7698 ALLEN      /7839/7698/7499/                3       4
          7900       7698 JAMES      /7839/7698/7900/                5       6
          7654       7698 MARTIN     /7839/7698/7654/                7       8
          7844       7698 TURNER     /7839/7698/7844/                9      10
          7521       7698 WARD       /7839/7698/7521/               11      12
          7782       7839 CLARK      /7839/7782/                    14      17
          7934       7782 MILLER     /7839/7782/7934/               15      16
          7566       7839 JONES      /7839/7566/                    18      27
          7902       7566 FORD       /7839/7566/7902/               19      22
          7369       7902 SMITH      /7839/7566/7902/7369/          20      21
          7788       7566 SCOTT      /7839/7566/7788/               23      26
          7876       7788 ADAMS      /7839/7566/7788/7876/          24      25
    The Lineage Model keeps track of all of a given nodes ancestors, so if all you need to find are the primary keys of a given node, it's really trivial: it's all in the lineage column.  If you want to find more information about those ancestors, then you can do a self-join, like this:
    SELECT    a.empno, a.ename, a.lineage
    FROM      emp  a
    JOIN      emp  d   ON  d.lineage  LIKE '%/' || a.empno || '/%'
    WHERE     d.ename  IN ('ADAMS')
    ORDER BY  d.ename
    ,         a.lineage
    Output:
         EMPNO ENAME      LINEAGE
          7839 KING       /7839/
          7566 JONES      /7839/7566/
          7788 SCOTT      /7839/7566/7788/
          7876 ADAMS      /7839/7566/7788/7876/
    The Nested Sets model is harder to understand.
    Imagine everyone in the hierarchy standing on a wide staircase, as if for a group picture; everyone on the same level standing on the same step.  Everyone is holding up an umbrella that is wide enough to cover himself and all the people who are under him in the hierarchy.  The people with no underlings have small umbrellas, denoted like this "<-SMITH->", and peole that manage others have bigger umbrellas, like this: <-------- JONES -------->.  So the group picture might look like this:
    <-------------------------------------------- KING --------------------------------------------->
      <---------------------- BLAKE --------------------->  <-- CLARK -->  <-------- JONES -------->
       <-ALLEN-> <-JAMES-> <-MARTIN-> <-TURNER-> <-WARD->    <-MILLER->     <-- FORD--> <--SCOTT-->
                                                                             <-SMITH->   <-ADAMS->
    Each parent's umbrella covers all of his descendants (children, grandchildren, etc.), and nobody else.
    Now draw vertical lines trom the edges of each umbrella downwards, and number those lines from left to right:
    <-------------------------------------------- KING ------------------------------------------------>
    |                                                                                                  |
    | <---------------------- BLAKE --------------------->  <-- CLARK ->   <-------- JONES ----------> |
    | |                                                  |  |          |   |                         | |
    | |<-ALLEN-> <-JAMES-> <-MARTIN-> <-TURNER-> <-WARD->|  |<-MILLER->|   |<-- FORD--> <--SCOTT---> | |
    | ||       | |       | |        | |        | |      ||  ||        ||   ||         | |          | | |
    | ||       | |       | |        | |        | |      ||  ||        ||   ||<-SMITH->| |<-ADAMS-> | | |
    | ||       | |       | |        | |        | |      ||  ||        ||   |||       || ||       | | | |
                                               1 1      11  11        11   112       22 22       2 2 2 2
    1 23       4 5       6 7        8 9        0 1      23  45        67   890       12 34       5 6 7 8
    The numbers corresponding to the left arnd right edges of each umbrella are what I called ns_low and ns_high in the table.  Each employyes ns_low and ns_high numbers will be inside the range of each of his ancestors ns_low and ns_high.
    To find the ancestors of a given node in the nested set model you can do this:
    SELECT   a.empno, a.ename, a.ns_low, a.ns_high
    FROM   emp  a
    JOIN      emp  d  ON  d.ns_low  BETWEEN  a.ns_low
                                    AND      a.ns_high
    WHERE     d.ename  IN ('ADAMS')
    ORDER BY  d.ename
    ,         a.ns_low
    Both the Lineage and Nested Sets models are good for tree structures only, whereas the Adjacency Model can handle other kinds of graphs, including graphs with loops.
    Both the Lineage and Nested Sets models can be very difficult to maintain if the hierarchy is re-organized.
    I'd like to repeat some of the warnings that others have made.  You could write separate code for each system (Oracle, SQL Server, ...) that you want to run in, and the code for each system will be more or less different.  You're looking for some code that will get the same results in all systems.  That code will be more complicated that the most complicated of the single-system versions, and it will be sloweer than the slwoest of the single-system versions.  You're giving up a lot of functionality, and probably also ease of maintenance, by writing code that has to work on multiple systems without changes.
    Here's how I created the emp table shown above from scott.emp:
    CREATE TABLE    emp
    AS
    WITH    connect_by_results  AS
        SELECT  empno, mgr, ename
        ,       LEVEL   AS lvl
        ,       ROWNUM  AS r_num
        ,       SYS_CONNECT_BY_PATH (empno, '/') || '/'   AS lineage
        FROM scott.emp
        START WITH mgr IS NULL
        CONNECT BY mgr = PRIOR empno
        ORDER SIBLINGS BY ename
    SELECT empno, mgr, ename, lineage
    ,       (2 * r_num) - lvl            AS ns_low
    ,       (2 * r_num) + ( 2 * (
                                    SELECT  COUNT (*)
                                    FROM    connect_by_results
                                    WHERE   lineage  LIKE '%/' || cbr.empno || '/%'
                        - (lvl + 1)      AS ns_high
    FROM connect_by_results   cbr
    This relies on the fact that the hierarchy in scott.emp has only one root (that is, a node with no parent).  Computing the Nested Sets numbers is a little more complicated if you can have multiple roots.

  • Spatial Query with multiple geometries from 2 tables

    Hi,
    I'm using Oracle 8.1.7. I am trying to do a spatial query on two tables with multiple geometries. There are two spatial tables. One made up of points and one made up of polygons. There are 829551 rows in the table of points and 1817795 rows in the table with polygons...
    I want to find all polygons where one of this points is within it...
    This query is pretty intensive querying two large spatial tables against each other and so I need to find the most efficient way of running this query. I've been running variations of my query for the last two week and every time it's bombed out with various errors after 12-24 hrs processing like out of memory, out of tablespace, out of processing, invalid index etc etc etc. I need to get this query run asap... Any tips would be gratefully appreciated..
    For the session running the query I've allocated 16M sort area with
    ALTER SESSION SET SORT_AREA_SIZE=16777216;
    Below is the query I'm running... How can I improve this please? BTW PARCEL_OVERLAPS contains the points and TP$_PARCEL_AREAS the polygons.
    SELECT lu.LNU_PARCEL_ID
         FROM
              seventy.PARCEL_OVERLAPS po,
              imap_topol.TP$_PARCEL_AREAS pa,
              TP$_PARCEL_CENTROID_AREA pca,
              TDCR_LAND_UNIT lu
         WHERE
              SDO_FILTER(po.geometry, pa.area,
              'querytype=WINDOW') = ’TRUE’ and
              sdo_within_distance(po.geometry,pa.area,'distance=0')='TRUE' and
              pa.delete_date is null and
              Lu.LNU_LAND_UNIT_UNIQUE_NUM = pca.CENTROID_ID and
              pa.AREA_ID = pca.AREA_ID and
              pca.DELETE_DATE IS NULL and
              pa.DELETE_DATE IS NULL;

    Albert,
    Thanks for your reply and the tips you've given. The tp$_parcel_areas table will always be bigger so I've changed the order to sdo_within_distance(pa.area,po.geometry,'distance=0')='TRUE'. The requested counts for those queries are
    12:26:29 [email protected]:SQL> select count(*)
    13:46:22 2 from seventy.PARCEL_OVERLAPS;
    COUNT(*)
    612
    13:48:12 [email protected]:SQL> select count(*)
    13:48:17 2 from imap_topol.TP$_PARCEL_AREAS pa,
    13:48:21 3 TP$_PARCEL_CENTROID_AREA pca
    13:48:21 4 where pca.DELETE_DATE IS NULL
    13:48:21 5 and pa.DELETE_DATE IS NULL
    13:48:21 6 and pa.AREA_ID = pca.AREA_ID;
    COUNT(*)
    1310665
    There was no reason for both filter and within_distance. I did try use the anyinteract but for some reason that does not return the desired results(I've added one id row as a test to make sure it returns desired results). Plus Oracle have recomended using the within distance for better performance..
    so the explan plan for
    14:38:37 [email protected]:SQL> EXPLAIN PLAN FOR
    14:38:50 2 SELECT lu.LNU_PARCEL_ID
    14:38:50 3 FROM
    14:38:50 4 seventy.PARCEL_OVERLAPS po,
    14:38:50 5 imap_topol.TP$_PARCEL_AREAS pa,
    14:38:50 6 TP$_PARCEL_CENTROID_AREA pca,
    14:38:50 7 TDCR_LAND_UNIT lu
    14:38:50 8 WHERE
    14:38:50 9 sdo_within_distance(pa.area,po.geometry,'distance=0')='TRUE' and
    14:38:50 10 pa.delete_date is null and
    14:38:50 11 Lu.LNU_LAND_UNIT_UNIQUE_NUM = pca.CENTROID_ID and
    14:38:50 12 pa.AREA_ID = pca.AREA_ID and
    14:38:50 13 pca.DELETE_DATE IS NULL and
    14:38:50 14 pa.DELETE_DATE IS NULL;
    is
    Plan Table
    | Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
    | SELECT STATEMENT | | 4G|32920G| 547M| | |
    | NESTED LOOPS | | 4G|32920G| 547M| | |
    | MERGE JOIN | | 547M| 2029G| 230124 | | |
    | SORT JOIN | | 1M| 36M| 85014 | | |
    | MERGE JOIN | | 1M| 36M| 50019 | | |
    | SORT JOIN | | 1M| 17M| 21650 | | |
    | TABLE ACCESS FULL |TP$_PARCE | 1M| 17M| 485 | | |
    | SORT JOIN | | 1M| 22M| 28369 | | |
    | TABLE ACCESS FULL |TDCR_LAND | 1M| 22M| 2127 | | |
    | SORT JOIN | | 42K| 160M| 145111 | | |
    | TABLE ACCESS FULL |TP$_PARCE | 42K| 160M| 12697 | | |
    | TABLE ACCESS FULL |PARCEL_OV | 817 | 3M| 1 | | |
    14:43:14 [email protected]:SQL> explain plan for
    14:43:23 2 SELECT pa.AREA_ID
    14:43:23 3 FROM seventy.PARCEL_OVERLAPS po,
    14:43:23 4 imap_topol.TP$_PARCEL_AREAS pa
    14:43:23 5 WHERE SDO_RELATE(po.geometry, pa.area,'mask=ANTINTERACT querytype=WINDOW') = 'TRUE'
    14:43:23 6 and pa.DELETE_DATE IS NULL;
    Plan Table
    | Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
    | SELECT STATEMENT | | 6M| 50G| 10M| | |
    | NESTED LOOPS | | 6M| 50G| 10M| | |
    | TABLE ACCESS FULL |PARCEL_OV | 817 | 3M| 1 | | |
    | TABLE ACCESS FULL |TP$_PARCE | 850K| 3G| 12697 | | |
    14:45:03 [email protected]:SQL> explain plan for
    14:45:04 2 SELECT pa.AREA_ID
    14:45:05 3 FROM seventy.PARCEL_OVERLAPS po,
    14:45:05 4 imap_topol.TP$_PARCEL_AREAS pa
    14:45:05 5 WHERE SDO_RELATE(pa.area, po.geometry,'mask=ANTINTERACT querytype=WINDOW') = 'TRUE'
    14:45:05 6 and pa.DELETE_DATE IS NULL;
    Plan Table
    | Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
    | SELECT STATEMENT | | 6M| 50G| 863554 | | |
    | NESTED LOOPS | | 6M| 50G| 863554 | | |
    | TABLE ACCESS FULL |TP$_PARCE | 850K| 3G| 12697 | | |
    | TABLE ACCESS FULL |PARCEL_OV | 817 | 3M| 1 | | |
    --------------------------------------------------------------------------------

  • Hierarchical Query with Rollup Sum (CONNECT BY with GROUP BY ROLLUP)

    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS VALUES ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS VALUES ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS VALUES ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS VALUES ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS VALUES ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS VALUES ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES VALUES ('4801001', 2000);
    INSERT INTO BALANCES VALUES ('4801002', 1000);
    INSERT INTO BALANCES VALUES ('4802001', 3000);
    INSERT INTO BALANCES VALUES ('4802002', 4000);What i need in this scenario is to run a hierarchical query, where for each node i compute the sum of all its children (In LEAF nodes which are the child accounts, this sum is the value in BALANCES itself). Final Result would be:
    TOT -> 10000
      ANA1 -> 3000
        4801001 -> 2000
        4801001 -> 1000
      ANA2 -> 7000
        4802001 -> 3000
        4802002 -> 4000I have tried various ways, and found out a workaround which works for a fixed amount of levels, basically it builds the hierarchy and computes the SYS_CONNECT_BY_PATH, then splits this as a regular expression and uses GROUP BY ROLLUP to compute the higher levels. Then i assemble it again, now with the computed values. Below is the example query:
    select level
        , NVL (vfinal.child_account,'TOTAL') ||' - '||
                            ( SELECT account_desc
                                FROM accounts
                               WHERE account_code = vfinal.child_acct ) account_name
         , to_char(sum_bal, 'fm999g999g999g990') as rolled_up_balance
      from
    select coalesce( princ.lvl3, princ.lvl2, princ.lvl1 ) child_acct
         , DECODE ( princ.lvl2 , NULL
                                     , NULL
                                     , DECODE ( princ.conta_lvl3, NULL
                                     , princ.conta_lvl1,princ.conta_lvl2 ) ) parent_acct
         , sum(princ.balance_amount) sum_bal
    from (
    select hier.lvl1
         , hier.lvl2
         , hier.lvl3
         , hier.parent_account
         , hier.account_code child_acc
         , bal.balance_amount
      from ( select level 
                  , sys_connect_by_path( account_code, '/' ) hierarchy_acct
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,3) lvl3
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,2) lvl2
                  , REGEXP_SUBSTR(sys_connect_by_path( account_code, '/' ),'[^/]+',1,1) lvl1
                  , account_code
                  , parent_account 
               from accounts acc
               where level <= 3
               start with parent_account is null
               connect by nocycle prior account = parent_account
               order siblings by parent_account
               ) hier
          , balances  bal
      where bal.cod_conta  = hier.account_code
    ) princ
    where princ.lvl1 is not null
    group by rollup ( princ.lvl1
                    , princ.lvl2
                    , princ.lvl3 )
    order by princ.conta_lvl1
           , princ.conta_lvl2
           , princ.conta_lvl3
    ) vfinal
    where child_acct is not null
    start with parent_acct is null
    connect by nocycle prior child_acct = parent_acctAll said and done, what i need is to do the same thing for infinite levels, because this query has 3 fixed levels. Do you know how can i structure a new query where, independently of the number of levels, the parent sums are all rolled up like this?
    Thanks a lot in advance! Best Regards!
    Thiago
    Edited by: Thiago on Sep 6, 2011 11:31 AM
    Edited by: Thiago on Sep 6, 2011 1:01 PM

    Hi,
    Thiago wrote:
    Hi all,
    Imagine the following scenario: i have an ACCOUNT table which holds accounts and their hierarchy (currently 5 levels), and a BALANCE table which holds balance records for the accounts. Only CHILD accounts (level 5) have records in the BALANCE table. Simple example:
    CREATE TABLE accounts (account_code VARCHAR2(30), parent_account VARCHAR2(30), account_desc VARCHAR2(400));
    CREATE TABLE balances (account_code VARCHAR2(30), balance_amount NUMBER(18,2));
    INSERT INTO ACCOUNTS ('TOT',NULL,'Total');
    INSERT INTO ACCOUNTS ('ANA1','TOT','General Expenses');
    INSERT INTO ACCOUNTS ('4801001','ANA1','Small Expenses');
    INSERT INTO ACCOUNTS ('4801002','ANA1','Transportation');
    INSERT INTO ACCOUNTS ('ANA2','TOT','Health Expenses');
    INSERT INTO ACCOUNTS ('4802001','ANA2','Healthcare');
    INSERT INTO ACCOUNTS ('4802002','ANA2','Facilities');
    INSERT INTO BALANCES ('4801001', 2000);
    INSERT INTO BALANCES ('4801001', 1000);
    INSERT INTO BALANCES ('4802001', 3000);
    INSERT INTO BALANCES ('4802001', 4000);
    Thanks for posting the CREATE TABLE and INSERT statements. Remember why you do it: so that the people who want to help you can re-create the problem and test their ideas. If the statments don't work, then they are not so useful. None of the INSERT statements you posted work: they all need a VALUES keyword. Please test those statments before you post them.
    Also, make sure that the reuslts you post correspond to the sample data you post. In your sample data, there are no rows in balances for account_codes '4801002' or '4802002'.
    I think you want something like this:
    WITH  connect_by_results      AS
         SELECT     CONNECT_BY_ROOT account_code     AS root_account_code
         ,     account_code
         FROM     accounts
                             -- NOTE: No START WITH clause
         CONNECT BY     parent_account     = PRIOR account_code
    SELECT       c.root_account_code     || ' -> '
                          || TO_CHAR (SUM (b.balance_amount))     AS txt
    FROM           connect_by_results  c
    LEFT OUTER JOIN      balances          b  ON  c.account_code = b.account_code
    GROUP BY  c.root_account_code
    ;

  • Query with multiple outer joins

    I had a doubt with whether the following kind of query is valid with multiple outer-joins. The format of the query is something like this:-
    select A.col1, B.col2
    from table1 A, table2 B, table3 C where
    A.col3=B.col4(+) and B.col5=C.col6(+)
    This would mean the follwoing with regard to outer-joins in the query.
    1) fetch records with col3 in table A matching or not matching col4 in table B
    2) fetch records with col5 in table B matching or not matching col6 in table C
    So, this query is valid?
    I hope, my question is clear.
    Please, help in solving the doubt.
    regards

    This is valid and it works fine

  • Hierarchical query with where clause

    Hi,
    How can I query hierarchically a query with WHERE clause? I have a table with three fields session_id,id and root_id.
    When I try with the following query,
    select id, level from relation
    where session_id = 79977
    connect by prior id = root_id start with id = 5042;
    It gets duplicate values.
    I want the query to show in the hierarchical manner with a filter condition using WHERE clause. Please help me how can I achieve this. If you know any link that describes more about this, please send it.
    Thanks in Advance.
    Regards,
    -Parmy

    Hi Sridhar Murthy an others,
    Thanks a lot for your/the answer. It's working for me. It saved a lot of other work around without the proper knowledge of hierarchical query. Please send me any link that describes these issues in detail and also I hope as I have mentioned in the other message, same cannot be achieved on views or ( on two different tables ???)
    Any way thanks for your reply,
    It's working for me.
    With happiness,
    -Parmy

  • How to create the query with multiple node types

    Hi,
    I am having an issue in creating a query to search multiple node types.
    The requirement is to query documents/pages of the type dam:Asset and cq:Page present under a path.
    I tried the following code snippet with no luck .
    path=/content
    1_type=cq:Page
    2_type=dam:Asset
    property=jcr:content/metadata/@cq:tags
    property.1_value=<tag Name>
    I was able to write a query with single type. However i could not find any documents/ materials with multipe types as shown above.
    Thanks in advance.
    Regards
    Sudhi

    I don't think multiple type is possible. Instead use super type like nt:base that will cover both page and asset.
    Yogesh
    www.wemblog.com

Maybe you are looking for