Hierarchial query problem
Hi,
We are trying to convert some old sql code to using Hierarchical queries, but am finding that the connect by expression is causing some errors for us. I have tried to follow the managedEmployees example from the web site but am not getting the parameters set correctly and keep getting the error below. I have attached our old code as well as the new code using Toplink. Please let me know if you see any issues with this.
Also, we have wrapped the Expression and ReadAllQuery classes with our own classes which is why we're not invoking those directly in the code below.
Thanks for the help,
Mark
Old SQL
DataExpression where = new DataExpression().get("organizationId").notNull();
String extraSQL = new String("");
extraSQL += " START WITH organization_id = " + orgId + " ";
extraSQL += " CONNECT BY PRIOR organization_id = parent_id ";
where.appendSQL(extraSQL);
Hierarchical query using Toplink
DataReadAllQuery raq = new DataReadAllQuery(Organization.class);
// Specify a START WITH expression
DataExpression startExpr = new DataExpression().get("organizationId").equal(orgId);
// Specifies a CONNECT BY expression
DataExpression connectBy = new DataExpression().get("organizationId").equal(new DataExpression().get("parentId"));
// Specifies an ORDER SIBLINGS BY vector
Vector order = new Vector();
raq.setHierarchicalQueryClause(startExpr, connectBy, order);
return QueryEngine.readAll(raq);
Error
TopLink Warning]: 2005.08.04 06:28:19.765--ServerSession(16237341)--Exception [TOPLINK-6073] (Oracle TopLink - 10g Developer Preview 3 (10.1.3.0 ) (Build 041116)): oracle.toplink.exceptions.QueryException
Exception Description: Malformed expression in query. Attempting to print an object reference into an SQL statement for query key [
Relation operator =
Query Key organizationId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}
Query Key parentId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}].
Query: ReadAllQuery(mil.usmc.mol.organization.Organization)
Aug 4, 2005 6:28:19 PM mil.usmc.mol.persistence.QueryEngine executeQuery
SEVERE: Error performing query. Nested exception is:
Exception Description: Malformed expression in query. Attempting to print an object reference into an SQL statement for query key [
Relation operator =
Query Key organizationId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}
Query Key parentId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}].
Query: ReadAllQuery(mil.usmc.mol.organization.Organization)
I've modified it to call the toplink classes directly, but still get the same error..
ReadAllQuery raq = new ReadAllQuery(Organization.class);
ExpressionBuilder expressionBuilder = raq.getExpressionBuilder();
Expression startExpr = expressionBuilder.get("organizationId").equal(orgId);
Expression connectBy = expressionBuilder.get("organizationId").equal(expressionBuilder.get("parentId"));
Vector order = new Vector();
raq.setHierarchicalQueryClause(startExpr, connectBy, order);
SessionManager manager = SessionManager.getManager();
Session session = manager.getSession("DEFAULT");
UnitOfWork uow = session.acquireUnitOfWork();
return (Collection) uow.executeQuery(raq);
[TopLink Info]: 2005.08.05 11:09:32.090--ServerSession(16237341)--TopLink, version: Oracle TopLink - 10g Developer Preview 3 (10.1.3.0 ) (Build 041116)
[TopLink Info]: 2005.08.05 11:09:34.200--ServerSession(16237341)--DEFAULT login successful
[TopLink Warning]: 2005.08.05 11:09:34.262--UnitOfWork(20039836)--Exception [TOPLINK-6073] (Oracle TopLink - 10g Developer Preview 3 (10.1.3.0 ) (Build 041116)): oracle.toplink.exceptions.QueryException
Exception Description: Malformed expression in query. Attempting to print an object reference into an SQL statement for query key [
Relation operator =
Query Key organizationId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}
Query Key parentId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}].
Query: ReadAllQuery(mil.usmc.mol.organization.Organization)
Local Exception Stack:
Exception [TOPLINK-6073] (Oracle TopLink - 10g Developer Preview 3 (10.1.3.0 ) (Build 041116)): oracle.toplink.exceptions.QueryException
Exception Description: Malformed expression in query. Attempting to print an object reference into an SQL statement for query key [
Relation operator =
Query Key organizationId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}
Query Key parentId
Base mil.usmc.mol.organization.Organization{DatabaseTable(t0)=DatabaseTable(ORGANIZATIONS)}].
Query: ReadAllQuery(mil.usmc.mol.organization.Organization)
Similar Messages
-
Hello All,
I have searched OTN and AskTom and saw many articles on hierarchial query but I just cannot seem to figure out how to apply it to my situation. Based on what I have read I do not believe CUBE or ROLLUP is the answer for this (maybe wrong..).
This data is only a small part of a much larger query used for auditing purposes, so i would need to incorporate the solution for this into the larger query.
Part of my problem is how to actual present this data in a format that would make sense to the end user, when included in a tabular (Excel) report.
I am trying to devise a way to verify that monthly payment is received for each product. In this case, some of the products are "created" under another product and then billed under a 3rd product.
To explain the table
Prod_1 - list all products
Prod_2 - lists only those products that are the parent of an item in the Prod_1 column.
Prod_3 - shows there is a relationship between an item in Prod_1 that is not in Prod_2.
There may be items in Prod_1 that have no relationship to Prod_2 or Prod_3 are those are just billed or *not getting billed BAD*
There are other cases where there is a item in Prod_2 that is the parent of one or more items in Prod_1 but not related to Prod_3 and those are billed.
There are other cases where there is a item in Prod_2 that is the parent of one or more items in Prod_1 but not related to Prod_3 and *not getting billed BAD*
For example:
+1-abcd-efgh, 3-qrst-uvwx and 5-ghij-klmn+ under Prod_1 is created under Prod_2 +1234-2f-maker-taker+ but billed under Prod_3 +87-test-789101+ at $139.11 MONTH_CHARGE.
CREATE TABLE PRODT ( design_id VARCHAR2(50), Prod_1 VARCHAR2(50), Prod_2 VARCHAR2(50), Prod_3 VARCHAR2(50), Month_Charge NUMBER );
INSERT INTO PRODT VALUES ( '8568','1-abcd-efgh', '1234-2f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '8569','2-ijkl-mnop', '5678-3f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '8570','3-qrst-uvwx', '1234-2f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '8571','4-yzab-cdef', '5678-3f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '8572','5-ghij-klmn', '1234-2f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '9421','1234-2f-maker-taker','','87-test-789101', 0 );
INSERT INTO PRODT VALUES ( '9588','5678-3f-maker-taker','','88-test-123456', 0 );
INSERT INTO PRODT VALUES ( '2531','87-test-789101', '', '1234-2f-maker-taker',139.11 );
INSERT INTO PRODT VALUES ( '2532','88-test-123456', '','5678-3f-maker-taker', 159.45 );
INSERT INTO PRODT VALUES ( '4531','76-test-101568', '', '',145.00 );
INSERT INTO PRODT VALUES ( '3528','6-abcd-efgh', '2234-1f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '3529','7-ijkl-mnop', '2234-1f-maker-taker','', 0 );
INSERT INTO PRODT VALUES ( '6261','2234-1f-maker-taker','','', 0 );
COMMIT; Desired Result:
Honestly - I am not sure of the best way to present it - definetly open for suggestions!
The table shows there is a relationship by Product Number, but the table does not make it clear that as in the example above that
all of the underlying products are being billed under +87-test-789101+ at $139.11 per month.
I must still show all of the Prod columns - so for my understanding Cube or Rollup is not a good fit(?).
That is what I am trying to accomplish - in other words I am getting paid for everything or not?
In my mind I see it something like this perhaps:
DESIGN_ID PROD_1 PROD_2 PROD_3 MONTH_CHARGE BILL_INDICATOR
8569 2-ijkl-mnop 5678-3f-maker-taker NULL 0 ? (Not sure how to indicate
8571 4-yzab-cdef 5678-3f-maker-taker NULL 0 what should be displayed
9588 5678-3f-maker-taker NULL 88-test-123456 0 in this new column to make
2532 88-test-123456 NULL 5678-3f-maker-taker 159.45 the Audit process simple *Help Needed*)Thanks for looking!
G
Edited by: GMoney on Aug 22, 2012 12:54 PM
Edited by: GMoney on Aug 22, 2012 12:57 PMFrank,
I was hoping you would cross paths with this post.
I am building on a TOP N query you helped me with in another post.
As I mentioned in my an initial post, I have products that may be in a hierarchical order (or stand alone) could be billed as primary or with secondary or tertiary products that are billed under the primary. Meaning the primary would have a dollar figure associated, and may or may not have secondary or tertiary products related to it.
To explain the table
Prod_1 - list all products
Prod_2 - lists only those products that are the parent of an item in the Prod_1 column.
Prod_3 - shows there is a relationship between an item in Prod_1 that is not in Prod_2.
There may be items in Prod_1 that have no relationship to Prod_2 or Prod_3 are those are just billed or not getting billed BAD
There are other cases where there is a item in Prod_2 that is the parent of one or more items in Prod_1 but not related to Prod_3 and those are billed.
There are other cases where there is a item in Prod_2 that is the parent of one or more items in Prod_1 but not related to Prod_3 and not getting billed BAD
My business requirement is to present all of the results from the initial query as well as adding in the dollar figures from an addition query against another financial table. I need to be able to make it perfectly clear to an end user auditor that each and every product is being billed, and clearly identify the secondary or tertiary items if there are any that fall under that primary product.
My real hung up here is the presentation of the data. I can easily see the correlation between them but it is not likely an end user would.
DESIGN_ID PROD_1 PROD_2 PROD_3 MONTH_CHARGE BILL_INDICATOR
8569 2-ijkl-mnop 5678-3f-maker-taker NULL 0 ? (Not sure how to indicate
8571 4-yzab-cdef 5678-3f-maker-taker NULL 0 what should be displayed
9588 5678-3f-maker-taker NULL 88-test-123456 0 in this new column to make
2532 88-test-123456 NULL 5678-3f-maker-taker 159.45 ; the Audit process simple *Help Needed*) Thanks for looking,
Greg -
Cosider the following record set from the emp table.
empno ename mgr
7839 KING
7566 SCOTT 7839
7566 BLAKE 7839
7782 CLARK 7839
If I use the following hierarchial query to populate a tree in Oracle forms
I will get the result as shown below.
Query
=====
select -1, level, ename, null, ename
from emp
where empno in (7839,7566,7698,7782)
start with ename = 'KING'
connect by mgr = prior empno;
Result
======
KING
JONES
BLAKE
CLARK
Here is my problem. Though diffrent employees can work under a manager,
we have some internal rules that assigns an order to each employee who
works under a manager. This helps us in identifying who should take
charge in the absence of a manager.
I have added one column to the emp table, in order to store the order in
which the employee reports to the manager.
Now the record set becomes
empno ename mgr emp_order
7839 KING 0
7566 SCOTT 7839 1
7566 BLAKE 7839 3
7782 CLARK 7839 2
Now I want the forms tree to be displayed as shown below.
KING
JONES
CLARK
BLAKE
(In short, I want the records in a particular level to be displayed
according to a pre-defined order, rather than getting them displayed
randomly).
Which query can I use for this purpose ?
Please help....
ShibuHi Guys,
Thanks a lot for your suggestions.
It really works great in SQL Plus.
I am familiar with Oracle Forms and I know how to use it if I want to build a tree in Forms.
Here is my requirement. I want to build the application using Oracle Portal. I know that there is something called 'Hierarchy' available in Portal. I don't know up to what extend it gives flexibility in programatically populating the tree.
Here is the scenario. I will use the hierarchial query with CONNECT SIBLINGS BY clause to populate the a tree which will show me employees in a department hierarchially.
Eg:
KING
SCOTT
BLAKE
SMITH
Now I like to show the projects assigned to each employee, which itself can be considered as another hierarchy.
Eg of Projects hierarchy.
Projects
Development
Oracle Applications
HRMS
Support
Intranet Applications
Suppose SCOTT is working in HRMS project, the tree should show as,
KING
SCOTT
Projects
Development
Oracle Applications
HRMS
BLAKE
SMITH
I can color code the node which will distinguish between an employee and his assignments.
Is there a way to achieve it in Oracle Portal using the 'Hierarchy' or what may be the best way to go (Applet etc...) ???
Thanks in advance for your help.
Shibu -
Hierarchy Query to get parent nodes?
Hi Everyone,
I want to write a hierarchy query which should give me the path starting from given node to its parents(Grand parents). below is the sample data and the output what i am expecting. and also the output what i am getting right now from my query.
CREATE TABLE RELATION (PARENT VARCHAR2(5),CHILD VARCHAR2(5) PRIMARY KEY);
--Data for the tree which starts from the root 'A'
Insert into RELATION (PARENT, CHILD) Values (NULL,'A');
Insert into RELATION (PARENT, CHILD) Values ('A', 'B');
Insert into RELATION (PARENT, CHILD) Values ('A', 'C');
Insert into RELATION (PARENT, CHILD) Values ('B', 'D');
Insert into RELATION (PARENT, CHILD) Values ('B', 'E');
Insert into RELATION (PARENT, CHILD) Values ('D', 'F');
Insert into RELATION (PARENT, CHILD) Values ('C', 'G');
--Data for the tree which starts from the root 'H'
Insert into RELATION (PARENT, CHILD) Values (NULL,'H');
Insert into RELATION (PARENT, CHILD) Values ('H', 'I');
Insert into RELATION (PARENT, CHILD) Values ('H', 'J');
Expected Output by passing values as 'F' which gives the path from bottom to up.
A<-B<-D<-F
My Query:
SELECT substr(sys_connect_by_path(child,'<-'),3)
FROM relation
WHERE connect_by_isleaf = 1
START WITH child = 'F'
CONNECT BY PRIOR parent = child
ORDER BY child;
Output of my query:
F<-D<-B<-A
I am getting the output in reverse order. i can use the reverse string function to reverse the string but the problem is the node can also contain the values like 'AC' 'BA'.. in future.
Can anyone please help me in getting the correct output.
Thank you in advance.I like ListAgg :D
with RELATION(PARENT,CHILD) as(
select NULL,'A' from dual union all
select 'A', 'B' from dual union all
select 'A', 'C' from dual union all
select 'B', 'D' from dual union all
select 'B', 'E' from dual union all
select 'D', 'F' from dual union all
select 'C', 'G' from dual union all
select NULL,'H' from dual union all
select 'H', 'I' from dual union all
select 'H', 'J' from dual)
SELECT ListAgg(child,'<-')
within group(order by Level desc) as revPath
FROM relation
START WITH child = 'F'
CONNECT BY PRIOR parent = child;
revPath
A<-B<-D<-F -
Hi All..
I have a hierarchy query with description as below
SQL> desc manager_entity;
Name Null? Type
MANAGER_ENTITY_ID NOT NULL NUMBER
MANAGER_ENTITY_TYPE_ID NOT NULL NUMBER
MANAGER_ENTITY_PARENT_ID NUMBER
CREATE_USER NOT NULL VARCHAR2(50)
CREATE_DATETIME NOT NULL DATE
LAST_UPDATE_USER NOT NULL VARCHAR2(50)
LAST_UPDATE_DATETIME NOT NULL DATE
MANAGER_ENTITY_LINK_ID NOT NULL NUMBERI got the correct relation between the parent and child using the below query
select me.manager_entity_id
, me.manager_entity_type_id
, me.manager_entity_parent_id
, me.manager_entity_link_id
, level
from manager_entity me
start with me.manager_entity_id=:p_id
connect by prior me.manager_entity_id=me.manager_entity_parent_idWhen I try to join this table with other 3 tables I’m unable to retrieve data. Description of the other 3 tables
SQL> desc manager_product;
Name Null? Type
MANAGER_PRODUCT_ID NOT NULL NUMBER
MANAGER_PRODUCT_NAME NOT NULL VARCHAR2(50)
MANAGER_ROOF_ID NOT NULL NUMBER
ACT_STRATEGY VARCHAR2(50)
ACT_SUB_STRATEGY VARCHAR2(50)
ACT_DATE_ENTERED DATE
ACT_INCEPTION_DATE DATE
ACT_PEER_GROUP VARCHAR2(50)
BACK_OFFICE_RISK_ID NUMBER
AREA_ID NUMBER
ACT_CREATE_DATE DATE
PROCESS_STOP_DATE DATE
TARGET_COMPLETION_DATE DATE
REVISIT_DATE DATE
CREATE_USER VARCHAR2(50)
CREATE_DATETIME DATE
LAST_UPDATE_USER VARCHAR2(50)
LAST_UPDATE_DATETIME DATE
SQL> desc manager_roof;
Name Null? Type
MANAGER_ROOF_ID NOT NULL NUMBER
MANAGER_ROOF_NAME NOT NULL VARCHAR2(50)
ROOF_COMPANY_ID NOT NULL NUMBER
CREATE_USER VARCHAR2(50)
CREATE_DATETIME DATE
LAST_UPDATE_USER VARCHAR2(50)
LAST_UPDATE_DATETIME DATE
SQL> desc investment_vehicle;
Name Null? Type
INVESTMENT_VEHICLE_ID NOT NULL NUMBER
INVESTMENT_VEHICLE_NAME NOT NULL VARCHAR2(255)
INVESTMENT_VEHICLE_ARRT_NAME VARCHAR2(255)
INVESTIER_SYSID NUMBER
INVESTIER_ID VARCHAR2(100)
MANAGER_PRODUCT_ID NUMBER
TRADING_STRUCTURE_TYPE_ID NUMBER
LEGAL_DESIGNATION_ID NUMBER
ADDITIONAL_INVEST_FORM_TYPE_ID NUMBER
INVESTMENT_VEH_CLASS_TYPE_ID NUMBER
ERISA_PLAN_ASSET_CATEGORY_ID NUMBER
SIDE_LETTER_FLAG CHAR(1)
INCEPTION_DATE DATE
ALLOW_ERISA_FLAG CHAR(1)
ALLOW_PLAN_ASSET_FLAG CHAR(1)
ALLOW_US_TAXABLE_INVESTOR_FLAG CHAR(1)
ALLOW_OFFSHORE_INVESTOR_FLAG CHAR(1)
SUB_DOC_DEADLINE NUMBER
WIRE_DEADLINE NUMBER
DOMICILE_COUNTRY_ID NUMBER
CREATE_USER VARCHAR2(50)
CREATE_DATETIME DATE
LAST_UPDATE_USER VARCHAR2(50)
LAST_UPDATE_DATETIME DATE
PERTRAC_DATA_VENDOR_ID VARCHAR2(255)
PERTRAC_DATA_VENDOR_NAME VARCHAR2(255)
FTS_NAME VARCHAR2(255)
MATLAB_MANAGER_NAME VARCHAR2(255)
ACT_CO_FUND_NAME VARCHAR2(255)
ACT_INVESTMENT_VEHICLE_NAME VARCHAR2(255)
SIDE_POCKET_PCT NUMBER
MAX_ILLIQUID_PCT NUMBER
CONTRIBUTION_OPENING_ID NUMBER
MANAGEMENT_FEE_PCT NUMBER
INCENTIVE_FEE_PCT NUMBER
SIDE_POCKET_NOTE VARCHAR2(4000)
FTS_ID NUMBERI was trying to join the other 3 tables with the main query as below..
select me.manager_entity_id
, me.manager_entity_type_id
, me.manager_entity_parent_id
, me.manager_entity_link_id
, level
from manager_entity me
, manager_roof mr
, manager_product mp
, investment_vehicle iv
where me.manager_entity_link_id= mr.manager_roof_id
and mr.manager_roof_id= mp.manager_roof_id
and mp.manager_product_id= iv.manager_product_id
start with me.manager_entity_id=:p_id
connect by prior me.manager_entity_id=me.manager_entity_parent_idHere manager_entity_link_id of manager_entity table represents(or has) the primary key of all the other 3 table..like
Enter value for p_id: 1
old 7: start with me.manager_entity_id=&p_id
new 7: start with me.manager_entity_id=1
MANAGER_ENTITY_ID MANAGER_ENTITY_TYPE_ID MANAGER_ENTITY_PARENT_ID
MANAGER_ENTITY_LINK_ID LEVEL
1 1008
14793 1
263 1009 1
19695 2
803 1010 263
7031783 3
MANAGER_ENTITY_ID MANAGER_ENTITY_TYPE_ID MANAGER_ENTITY_PARENT_ID
MANAGER_ENTITY_LINK_ID LEVEL
804 1010 263
7031782 3
805 1010 263
7031781 3The above is the output for the hierarchy query
Here the MANAGER_ENTITY_LINK_ID has values (14793, 19695, 7031783 , 7031782 , 7031781)
Where 14793 is the manager_roof_id in manager_roof_table
19695 is the manager_product_id in the manager_product table
7031783 , 7031782 , 7031781 are the investment_vehicle_id’s in the investment_vehicle table…
In the output I need to retrieve manager_roof_name, manager_product_name, investment_vehicle_name..
Thanks in advance
HTH
Edited by: user10280715 on Dec 3, 2008 11:55 AMThe reason result show as no rows selected is your first insert. If fails since column list has 3 columns while values list has 4 values. You probably missed "ORA-00913: too many values" error:
SQL> drop table manager_entity
2 /
Table dropped.
SQL> create table manager_entity(manager_entity_id number,manager_entity_type_id number,manager_entity_parent_id number,manager_entity_link_id number)
2 /
Table created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_link_id)
2 values(1,1008,null,14793)
3 /
insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_link_id)
ERROR at line 1:
ORA-00913: too many values
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(263, 1009, 1, 19695)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(803, 1010, 263, 7031783)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(804, 1010, 263, 7031782)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(805, 1010, 263, 7031781)
3 /
1 row created.
SQL> drop table manager_roof
2 /
Table dropped.
SQL> create table manager_roof(manager_roof_id number,manager_roof_name varchar2(20))
2 /
Table created.
SQL> insert into manager_roof(manager_roof_id,manager_roof_name)
2 values(14793,'roof')
3 /
1 row created.
SQL> drop table manager_product
2 /
Table dropped.
SQL> create table manager_product(manager_product_id number,manager_product_name varchar2(20),manager_roof_id number)
2 /
Table created.
SQL> Insert into manager_product(manager_product_id,manager_product_name,manager_roof_id)
2 Values(19695,'product1', 14793)
3 /
1 row created.
SQL> drop table investment_vehicle
2 /
Table dropped.
SQL> create table investment_vehicle(investment_vehicle_id number,manager_product_id number,investment_vehicle_name varchar2(20))
2 /
Table created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031781,19695,'inv1')
3 /
1 row created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031782,19695,'inv3')
3 /
1 row created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031783,19695,'inv3')
3 /
1 row created.
SQL> COMMIT
2 /
Commit complete.
SQL>
SQL> select me.manager_entity_id
2 , me.manager_entity_type_id
3 , me.manager_entity_parent_id
4 , me.manager_entity_link_id
5 , level
6 from manager_entity me
7 start with me.manager_entity_id=&p_id
8 connect by prior me.manager_entity_id=me.manager_entity_parent_id
9
SQL> /
Enter value for p_id: 1
old 7: start with me.manager_entity_id=&p_id
new 7: start with me.manager_entity_id=1
no rows selectedAs soon as you fix the error:
SQL> drop table manager_entity
2 /
Table dropped.
SQL> create table manager_entity(manager_entity_id number,manager_entity_type_id number,manager_entity_parent_id number,manager_entity_link_id number)
2 /
Table created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(1,1008,null,14793)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(263, 1009, 1, 19695)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(803, 1010, 263, 7031783)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(804, 1010, 263, 7031782)
3 /
1 row created.
SQL> insert into manager_entity(manager_entity_id,manager_entity_type_id,manager_entity_parent_id,manager_entity_link_id)
2 values(805, 1010, 263, 7031781)
3 /
1 row created.
SQL> drop table manager_roof
2 /
Table dropped.
SQL> create table manager_roof(manager_roof_id number,manager_roof_name varchar2(20))
2 /
Table created.
SQL> insert into manager_roof(manager_roof_id,manager_roof_name)
2 values(14793,'roof')
3 /
1 row created.
SQL> drop table manager_product
2 /
Table dropped.
SQL> create table manager_product(manager_product_id number,manager_product_name varchar2(20),manager_roof_id number)
2 /
Table created.
SQL> Insert into manager_product(manager_product_id,manager_product_name,manager_roof_id)
2 Values(19695,'product1', 14793)
3 /
1 row created.
SQL> drop table investment_vehicle
2 /
Table dropped.
SQL> create table investment_vehicle(investment_vehicle_id number,manager_product_id number,investment_vehicle_name varchar2(20))
2 /
Table created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031781,19695,'inv1')
3 /
1 row created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031782,19695,'inv3')
3 /
1 row created.
SQL> Insert into investment_vehicle(investment_vehicle_id,manager_product_id,investment_vehicle_name)
2 Values(7031783,19695,'inv3')
3 /
1 row created.
SQL> COMMIT
2 /
Commit complete.
SQL>
SQL> select me.manager_entity_id
2 , me.manager_entity_type_id
3 , me.manager_entity_parent_id
4 , me.manager_entity_link_id
5 , level
6 from manager_entity me
7 start with me.manager_entity_id=&p_id
8 connect by prior me.manager_entity_id=me.manager_entity_parent_id
9
SQL> /
Enter value for p_id: 1
old 7: start with me.manager_entity_id=&p_id
new 7: start with me.manager_entity_id=1
MANAGER_ENTITY_ID MANAGER_ENTITY_TYPE_ID MANAGER_ENTITY_PARENT_ID MANAGER_ENTITY_LINK_ID LEVEL
1 1008 14793 1
263 1009 1 19695 2
803 1010 263 7031783 3
804 1010 263 7031782 3
805 1010 263 7031781 3
SQL> SY. -
Hi All,
I have below tables,
Tables
1 Employees Type (Tells About Employees Designation)
2.Employee Details (Tells Employee Details)
3.Employee Relation (Tells Relationship between Employees)
Hierarchy
ARC (SENIOR MANAGER)
SUN (MANAGER)
MOON (TECH LEAD)
LITE (EMPLOYEE)
RAG (TECH LEAD)
BESH (TECH LEAD)
CHESH (EMPLOYEE)
PRASAD (EMPLOYEE)
1 Employees Type Data
Type No||Type Name
1|Employee
2|Tech Lead
3|Manager
4|Senior Manager
2.Employee Details
Emp No||Emp Name|Employee Type
10|ARC|4
20|SUN|3
30|RAG|2
40|PRASAD|1
50|MOON|2
60|LITE|1
70|CHESH|1
80|BESH|2
3. Employee Relation
Relation Number|Emp No|Prnt_Relation Number
1|10|NULL
2|20|1
3|30|1
4|40|1
5|50|2
6|60|2
7|70|3
8|80|3
These are my tables structure,
Now I want Hierarchial Query for below,
Input will be Relation Number,
if I give relation number as input I want to display all immediate childern that are Tech Leads and Employees only (it should ignore if it is having any Managers in the result set)
Ex: -
Input is relation number from Employee Relation Table,
If I give input as *1*
Output Should be,
Relation Number|Employee_id|Employee Name
3|30|Rag
7|70|Besh
8|80|Chesh
If I give input as *2*
Output Should be,
Relation Number|Employee_id|Employee Name
5|50|MOON
6|60|LITE,
If I give input as *4*
Output Should be,
Relation Number|Employee_id|Employee Name
<NO Rows Returned>
Thanks,Hi,
with emp_type as ( select 1 type_id, 'Employee' emp_type from dual
union
select 2 type_id, 'Tech Lead' emp_type from dual
union
select 3 type_id, 'Manager' emp_type from dual
union
select 4 type_id, 'Senior Manager' emp_type from dual),
emp_details as ( select 10 emp_no, 'ARC' fname, 4 type1 from dual
union
select 20 emp_no, 'SUN' fname, 3 type1 from dual
union
select 30 emp_no, 'RAG' fname, 2 type1 from dual
union
select 40 emp_no, 'PRASAD' fname, 1 type1 from dual
union
select 50 emp_no, 'MOON' fname, 2 type1 from dual
union
select 60 emp_no, 'LITE' fname, 1 type1 from dual
union
select 70 emp_no, 'CHESH' fname, 1 type1 from dual
union
select 80 emp_no, 'BESH' fname, 2 type1 from dual),
Emp_Relation as (
select 1 Relation, 10 emp_no1, null parent_Relation from dual
union
select 2 Relation, 20 emp_no1, 1 parent_Relation from dual
union
select 3 Relation, 30 emp_no1, 1 parent_Relation from dual
union
select 4 Relation, 40 emp_no1, 1 parent_Relation from dual
union
select 5 Relation, 50 emp_no1, 2 parent_Relation from dual
union
select 6 Relation, 60 emp_no1, 2 parent_Relation from dual
union
select 7 Relation, 70 emp_no1, 3 parent_Relation from dual
union
select 8 Relation, 80 emp_no1, 8 parent_Relation from dual)
select type_id, emp_type,
emp_no, fname, relation, parent_relation
from EMP_DETAILS, EMP_TYPE, EMP_RELATION
WHERE TYPE_ID = type1
AND EMP_NO = EMP_NO1
AND LEVEL = 2
CONNECT BY PRIOR RELATION = PARENT_RELATION
START WITH RELATION = :P_RELATION
--START WITH PARENT_RELATION IS NULL -- If want to display the complete heirarchy remove comments for this line and remove "and level = 2" and "START WITH RELATION = :P_RELATION"For p_relation = 1
TYPE_ID EMP_TYPE EMP_NO FNAME RELATION PARENT_RELATION
3 Manager 20 SUN 2 1
2 Tech Lead 30 RAG 3 1
1 Employee 40 PRASAD 4 1
3 rows selected.Not sure how do you get the following and it's not clear on what basis.
If I give input as *1*
Output Should be,
Relation Number|Employee_id|Employee Name
3|30|Rag
7|70|Besh
8|80|CheshFor p_relation = 2
TYPE_ID EMP_TYPE EMP_NO FNAME RELATION PARENT_RELATION
2 Tech Lead 50 MOON 5 2
1 Employee 60 LITE 6 2
2 rows selected.For p_relation = 3
TYPE_ID EMP_TYPE EMP_NO FNAME RELATION PARENT_RELATION
1 Employee 70 CHESH 7 3
1 row selected.For p_relation = 4
no rows selected.Hope this helps
Best Regards
Arif Khadas
Edited by: Arif Khadas on Jun 29, 2010 12:47 PM -
Hello APEX people,
I posted my problem here:
Designing LOV Query Problem
What I have is a sequence like this:
CREATE SEQUENCE
DR_SEQ_FIRST_SCHEDULE_GROUP
MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
CACHE 6 ORDER CYCLE ;
What I need would be a SQL query returning all possible values oft my sequence like:
1
2
3
4
5
6
7
I want to use it as a source for a LOV...
The reason why I use the cycling sequence is: My app uses it to cycle scheduling priorities every month to groups identified by this number (1-7).
In the Admin Form, I want to restrict the assignment in a user friendly way - a LOV.
Thanks
JohannHere ist the solution (posted by michales in the PL/SQL forum):
SQL> CREATE SEQUENCE
dr_seq_first_schedule_group
MINVALUE 1 MAXVALUE 7 INCREMENT BY 1 START WITH 1
CACHE 6 ORDER CYCLE
Sequence created.
SQL> SELECT LEVEL sn
FROM DUAL
CONNECT BY LEVEL <= (SELECT max_value
FROM user_sequences
WHERE sequence_name = 'DR_SEQ_FIRST_SCHEDULE_GROUP')
SN
1
2
3
4
5
6
7
7 rows selected. -
SQL+-MULTI TABLE QUERY PROBLEM
HAI ALL,
ANY SUGGESTION PLEASE?
SUB: SQL+-MULTI TABLE QUERY PROBLEM
SQL+ QUERY GIVEN:
SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
DLC_POLYMORPHS_NORMAL_VALUE FROM PATIENTS_MASTER1, HAEMATOLOGY1,
DIFFERENTIAL_LEUCOCYTE_COUNT1
WHERE PATIENT_NUM = HMTLY_PATIENT_NUM AND PATIENT_NUM = DLC_PATIENT_NUM AND PATIENT_NUM
= &PATIENT_NUM;
RESULT GOT:
&PATIENT_NUM =1
no rows selected
&PATIENT_NUM=2
no rows selected
&PATIENT_NUM=3
PATIENT_NUM 3
PATIENT_NAME KKKK
HMTLY_TEST_NAME HAEMATOLOGY
HMTLY_RBC_VALUE 4
HMTLY_RBC_NORMAL 4.6-6.0
DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
DLC_POLYMORPHS_VALUE 60
DLC_POLYMORPHS_NORMAL_VALUE 40-65
ACTUAL WILL BE:
&PATIENT_NUM=1
PATIENT_NUM 1
PATIENT_NAME BBBB
HMTLY_TEST_NAME HAEMATOLOGY
HMTLY_RBC_VALUE 5
HMTLY_RBC_NORMAL 4.6-6.0
&PATIENT_NUM=2
PATIENT_NUM 2
PATIENT_NAME GGGG
DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
DLC_POLYMORPHS_VALUE 42
DLC_POLYMORPHS_NORMAL_VALUE 40-65
&PATIENT_NUM=3
PATIENT_NUM 3
PATIENT_NAME KKKK
HMTLY_TEST_NAME HAEMATOLOGY
HMTLY_RBC_VALUE 4
HMTLY_RBC_NORMAL 4.6-6.0
DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
DLC_POLYMORPHS_VALUE 60
DLC_POLYMORPHS_NORMAL_VALUE 40-65
4 TABLES FOR CLINICAL LAB FOR INPUT DATA AND GET REPORT ONLY FOR TESTS MADE FOR PARTICULAR
PATIENT.
TABLE1:PATIENTS_MASTER1
COLUMNS:PATIENT_NUM, PATIENT_NAME,
VALUES:
PATIENT_NUM
1
2
3
4
PATIENT_NAME
BBBB
GGGG
KKKK
PPPP
TABLE2:TESTS_MASTER1
COLUMNS:TEST_NUM, TEST_NAME
VALUES:
TEST_NUM
1
2
TEST_NAME
HAEMATOLOGY
DIFFERENTIAL LEUCOCYTE COUNT
TABLE3:HAEMATOLOGY1
COLUMNS:
HMTLY_NUM,HMTLY_PATIENT_NUM,HMTLY_TEST_NAME,HMTLY_RBC_VALUE,HMTLY_RBC_NORMAL_VALUE
VALUES:
HMTLY_NUM
1
2
HMTLY_PATIENT_NUM
1
3
MTLY_TEST_NAME
HAEMATOLOGY
HAEMATOLOGY
HMTLY_RBC_VALUE
5
4
HMTLY_RBC_NORMAL_VALUE
4.6-6.0
4.6-6.0
TABLE4:DIFFERENTIAL_LEUCOCYTE_COUNT1
COLUMNS:DLC_NUM,DLC_PATIENT_NUM,DLC_TEST_NAME,DLC_POLYMORPHS_VALUE,DLC_POLYMORPHS_
NORMAL_VALUE,
VALUES:
DLC_NUM
1
2
DLC_PATIENT_NUM
2
3
DLC_TEST_NAME
DIFFERENTIAL LEUCOCYTE COUNT
DIFFERENTIAL LEUCOCYTE COUNT
DLC_POLYMORPHS_VALUE
42
60
DLC_POLYMORPHS_NORMAL_VALUE
40-65
40-65
THANKS
RCS
E-MAIL:[email protected]
--------I think you want an OUTER JOIN
SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
DLC_POLYMORPHS_NORMAL_VALUE
FROM PATIENTS_MASTER1, HAEMATOLOGY1, DIFFERENTIAL_LEUCOCYTE_COUNT1
WHERE PATIENT_NUM = HMTLY_PATIENT_NUM (+)
AND PATIENT_NUM = DLC_PATIENT_NUM (+)
AND PATIENT_NUM = &PATIENT_NUM;Edited by: shoblock on Nov 5, 2008 12:17 PM
outer join marks became stupid emoticons or something. attempting to fix -
Get only last level in SQL Hierarchy Query
Hi,
How to get only the last level in Oracle SQL Hierarchy Query?
ThanksHi,
1007372 wrote:
Hi,
How to get only the last level in Oracle SQL Hierarchy Query?Depending on your requirements:
WHERE CONNECT_BY_ISLEAF = 1
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
If you can show what you want to do using commonly available tables (such as scott.emp, which contains a hierarchy), then you don't need to post any sample data; just the results and the explanation.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0). This is always important, but especially so with CONNECT BY queries, because every version since Oracle 7 has had significant improvements in this area.
See the forum FAQ {message:id=9360002} -
Sort siblings of a hierarchial query in oracle8i
Hi,
I have a basic hierarchial query like the following:
select *
from users_table
start with userid = user
connect by manager = prior userid
I would like to sort the employees by name under their manager. Is there an easy way to do this in Oracle8i. I cannot use the ORDER SIBLINGS BY clause until Oracle9i. Thanks for your help.http://www.quest-pipelines.com/pipelines/plsql/archives.htm#code16
-
Hierarchy Query For Full Tree ?
Hi Everyone,
I want to write a hierarchy query which should give me the whole path starting from root node to each individual nodes by passing value of any individual tree member. below is the sample data and the output what i am expecting. and also the output what i am getting right now from my query.
CREATE TABLE RELATION (PARENT VARCHAR2(1),CHILD VARCHAR2(1) PRIMARY KEY);
--Data for the tree which starts from the root 'A'
Insert into RELATION (PARENT, CHILD) Values (NULL,'A');
Insert into RELATION (PARENT, CHILD) Values ('A', 'B');
Insert into RELATION (PARENT, CHILD) Values ('A', 'C');
Insert into RELATION (PARENT, CHILD) Values ('B', 'D');
Insert into RELATION (PARENT, CHILD) Values ('B', 'E');
Insert into RELATION (PARENT, CHILD) Values ('D', 'F');
Insert into RELATION (PARENT, CHILD) Values ('C', 'G');
--Data for the tree which starts from the root 'H'
Insert into RELATION (PARENT, CHILD) Values (NULL,'H');
Insert into RELATION (PARENT, CHILD) Values ('H', 'I');
Insert into RELATION (PARENT, CHILD) Values ('H', 'J');
Expected Output by passing values as 'C' which gives the whole tree where the node C is present:
A
A->B
A->C
A->B->D
A->B->E
A->C->G
A->B->D->F
My Query:
select
sys_connect_by_path(child,'->') tree
from
relation
--where (parent ='C' or child='C')
start with
parent is null
connect by
prior child = parent
order by tree;
Output of my query:
->A
->A->B
->A->B->D
->A->B->D->F
->A->B->E
->A->C
->A->C->G
->H
->H->I
->H->J
I am not able to add the condition for the query so that i can get only rows of the tree where the nod 'C' is present. i am just getting whole data from the table with all the unwanted trees.
Can anyone please help me in getting the correct output.
Thank you in advance.odie_63 wrote:
Another solution, involving analytics : Hierarchical queries and analytic functions do not mix well together in 10g:
SQL> select * from v$version
2 /
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
PL/SQL Release 10.2.0.4.0 - Production
CORE 10.2.0.4.0 Production
TNS for 32-bit Windows: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production
SQL> SELECT tree
2 FROM (
3 select sys_connect_by_path(child,'->') tree,
4 max(case when child = 'C' then connect_by_root(child) end) over() root1,
5 connect_by_root(child) root2
6 from relation
7 start with parent is null
8 connect by prior child = parent
9 )
10 WHERE root1 = root2
11 ;
from relation
ERROR at line 6:
ORA-00600: internal error code, arguments: [qctcte1], [0], [], [], [], [], [], []
SQL> Although it is much better in 11g:
SQL> select * from v$version
2 /
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL> SELECT tree
2 FROM (
3 select sys_connect_by_path(child,'->') tree,
4 max(case when child = 'C' then connect_by_root(child) end) over() root1,
5 connect_by_root(child) root2
6 from relation
7 start with parent is null
8 connect by prior child = parent
9 )
10 WHERE root1 = root2
11 ;
TREE
->A
->A->B
->A->B->D
->A->B->D->F
->A->B->E
->A->C
->A->C->G
7 rows selected.
SQL> SY. -
Oracle HRMS Organization Hierarchy query
Dear All,
Could any one provide me Oracle HRMS Organization Hierarchy query, please find the attachment of navigation.
and please find the following query i developed, here i am getting all hierarchies as per attachment.
SELECT distinct pose.D_PARENT_NAME , pose.org_structure_version_id,pose.organization_id_parent,
haou2.ORGANIZATION_ID PARENT_ID_ORG,
pose.D_CHILD_NAME
FROM apps.per_organization_structures_v pos
, apps.per_org_structure_versions posv
, apps.per_org_structure_elements_v pose
, apps.hr_all_organization_units haou2
WHERE pos.name = 'PIC HR ORGANIZATION HIERARCHY'
AND pose.D_PARENT_NAME='CHAIRMAN'
AND pose.org_structure_version_id = posv.org_structure_version_id
AND posv.organization_structure_id = pos.organization_structure_id
AND haou2.organization_id = pose.organization_id_child
and pose.D_PARENT_NAME=nvl(:P_PARENT_NAME,pose.D_PARENT_NAME)
and pose.D_CHILD_NAME=nvl(:P_CHILD_NAME,pose.D_CHILD_NAME)
and sysdate between posv.DATE_FROM and nvl(posv.DATE_TO,sysdate)
CONNECT BY PRIOR pose.organization_id_parent = pose.organization_id_child
can any one help me on this??
Thanks in advance..
Best RegardsHi,
Try the following query and adapt as required for your instance (I've used Vision instance):
SELECT DISTINCT pose.d_parent_name,
pose.organization_id_parent,
pose.d_child_name,
pose.organization_id_child
FROM
per_org_structure_elements_v pose,
per_org_structure_versions posv,
per_organization_structures pos
WHERE pos.name = 'Primary Reporting Hierarchy'
AND posv.version_number = 1
AND pos.business_group_id = 202
AND posv.organization_structure_id = pos.organization_structure_id
AND pose.org_structure_version_id = posv.org_structure_version_id
AND pose.business_group_id = pos.business_group_id
AND posv.business_group_id = pose.business_group_id
START WITH pose.d_parent_name = 'Vision Operations'
CONNECT BY NOCYCLE PRIOR pose.organization_id_child = pose.organization_id_parent
ORDER BY pose.organization_id_parent, pose.organization_id_child
HTH,
Regards,
Rajen.
P.S: Please mark response as Helpful/Correct (Answered) if it resolves or helps to resolve your issue. Thks. -
Hi All,
I need supervisor assignment hierarchy query(HRMS), for generating report.
can someone help me on this??
Any help is greately appreciated.
Regards
GopiHello everyone
When i am trying to execute following query, i am getting an error like
ORA-01473
Cannot Have Sub Queries in Connect By Clause
It display the hierarchy starting from our board of directors in a descending manner
SELECT LPAD ('->', 8 * (LEVEL - 1))
|| (SELECT DISTINCT full_name
FROM per_all_people_f
WHERE person_id = paf.person_id
AND PERSON_TYPE_ID '1123' -- 1123 = 'Ex-Employee'
AND SYSDATE BETWEEN effective_start_date
AND effective_end_date)
TREE
FROM per_all_assignments_f paf
WHERE SYSDATE BETWEEN paf.effective_start_date
AND paf.effective_end_date
AND paf.primary_flag = 'Y'
and paf.person_id in
(select pf.person_id from per_all_people_f pf where pf.PERSON_TYPE_ID '1123' and paf.person_id = pf.person_id
AND SYSDATE BETWEEN pf.effective_start_date
AND pf.effective_end_date
START WITH paf.person_id = (select person_id from per_all_people_f where last_name ='Board of') -- Board of Directors
CONNECT BY PRIOR paf.person_id = paf.supervisor_id
AND paf.primary_flag = 'Y'
AND paf.person_id in (select person_id from per_all_people_f pf where paf.person_id = pf.person_id and pf.PERSON_TYPE_ID'1123')
AND SYSDATE BETWEEN paf.effective_start_date
AND paf.effective_end_date
Could anyone help me on this??
Regards
Gopi -
Query problem with hierarchy filter
Hello everybody,
i have a problem with a BEx Query 3.5 on a BW 7.01-System. This query includes the cha cost category as free characteristic which is filtered on a node. When we execute this query everythin works correktly. When I now select a filter value in BEx fpr this char the formula value in the row does not change. When I drilldown on this char the correct data was shown. This problem occurs only with this hierarchy node. With other selected nodes this problem does not occur.
We have regenerated this query in rsrt but that don't fix this issue.
Has anybody an answer?hello,
the problem is known. You may check whether implementing the following note solves the issue:
1434532
best regards,
Jerome -
A slightly different running sum in a hierarchy query
Hi,
I've got stuck with this problem since quite some time, so pls help:
I am basically trying to rollup/aggregate values from the lower level nodes to the upper level nodes in a hierarchy. But this aggregate is a bit different than a plain rollup of values.
create table ent_rel (parent number, child number, child_amount number);
insert into ent_rel
select null, 100, null from dual
union all select 100, 101, null from dual
union all select 101, 102, 20 from dual
union all select 102, 103, null from dual
union all select 103, 104, null from dual
union all select 104, 105, null from dual
union all select 105, 106, 40 from dual
union all select 106, 107, null from dual
union all select 107, 108, 20 from dual
union all select 107, 109, 10 from dual
union all select 101, 203, null from dual
union all select 203, 205, 50 from dual
union all select 205, 207, null from dual
union all select 207, 209, null from dual
union all select 209, 210, 10 from dual
commit;
select RPAD(' ', (LEVEL - 1) * 2, '-') || child child
,level
,child_amount
from ent_rel
start with parent is null
connect by prior child = parent
CHILD LEVEL CHILD_AMOUNT
100 1
--101 2
----102 3 20
------103 4
--------104 5
----------105 6
------------106 7 40
--------------107 8
----------------108 9 20
----------------109 9 10
----203 3
------205 4 50
--------207 5
----------209 6
------------210 7 10
Now, I need a SQL query or even a simple PL/SQL code to get the DESIRED_AMOUNT field as shown below:
Pls note that there might be many more parallel branches to a node, but I've kept it simple just to get the concept.
CHILD LEVEL CHILD_AMOUNT DESIRED_AMOUNT
100 1 70
--101 2 70
----102 3 20 20
------103 4 40
--------104 5 40
----------105 6 40
------------106 7 40 40
--------------107 8 30
----------------108 9 20 20
----------------109 9 10 10
----203 3 50
------205 4 50 50
--------207 5 10
----------209 6 10
------------210 7 10 10
Thanks a lot in advance.
thanks and regards,
KnlHi,
Welcome to the forum!
Thanks for posting the CREATE TABLE and INSERT statements! That's very helpful.
It's also helpful if you format your code and output. When posting formatted text on this site, type these 6 characters:
\(all small letters, inside curly brackets) to keep the site from compressing the spaces.
You can do two CONNECT BY queries: one to get the desired amount, and the other like you're already doing, to get the indented child column. The first will differ in that it has no START WITH clause, which means every node in your table will be the root of a tree, and that there's an additional CONNECT BY condition to quit looking for descendants as soon as an amount is found. This corresponds to your apparant requirement that the desired_amount is the amount, if it is not NULL, and only otherwise is the sum of the desired_amounts of one's descendants.WITH desired_amount_tree AS
SELECT CONNECT_BY_ROOT child AS root
, child
, child_amount
FROM ent_rel
CONNECT BY PRIOR child = parent
AND PRIOR child_amount IS NULL
, got_desired_amount AS
SELECT root
, SUM (child_amount) AS desired_amount
FROM desired_amount_tree
GROUP BY root
select RPAD ( ' '
, (LEVEL - 1) * 2
) || e.child AS child
, level
, e.child_amount
, desired_amount
from ent_rel e
JOIN got_desired_amount d ON e.child = d.root
start with parent is null
connect by prior child = parent
It's usually more efficient to do join after doing the CONNECT BY. For better performance, try doing your original query by itself, and then joining its result set to got_desired_amount.
Of course, it would be a lot more efficient if we could eliminate the extra CONNECT BY query. That might be possible using MODEL or (starting in Oracle 11.2) a recursive sub-query.
Maybe you are looking for
-
Bootcamp 3.0, 3.1, and 3.2 ALL crash my windows 7
I have been trying to solve this problem for a little while now, but to no avail. I have Win 7 x64 ultimate installed on my Early 2009 Mac Pro, running the latest Snow Leopard. I'm using the new ATI 5870 card, which is great, but if I install any ver
-
Hi, i have created a query by copying from other query and transported it.But i couldnt open the new query. I couldnt understand what the problem is. first query is working fine. Transportation is successful. pls, help me in this shylaja.
-
MI424WR - DNS Host Name Resolution
I have added several DNS entries in the DNS Server section of the MI424WR. These are for my network printer, and I have renamed several Android devices to give them names. When I try to ping any host name that I added to the DNS Server section it doe
-
HT4759 Why can't I download the iOS6 on my iPad?
I'm unable to update software to iOS on my iPad. It's running 5.1.1 and says it's up to date. Also have iCloud on both. I have the first iPad 16.9 and have also bought more space. I've updated my iPhone. Which I'm wondering is why my photos stopped
-
i need help in this info, how i can get the serials for the apps in creative cloud? thank you!