Connect by prior return unnecessary rows
Hello,
I am using oracle 9.2
my query looks like this:
SELECT *
FROM book_items t
where cust_id = 2305240
and sort_key is not null
CONNECT BY PRIOR item_id = parent_id
START WITH t.item_id = 193
ORDER SIBLINGS BY sort_key
the problem is, when I have a father that has no sort_key (null) then it doesn't come up in the result, BUT his child does! they have a sort key, but why do I see them if the father is not exist in the result, it makes no sense to me...?
How can I fix this, if the father doesn't comes up, I don't need his child's?
Thanks.
It's documented behaviour that:
Oracle processes hierarchical queries as follows:
A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.
The CONNECT BY condition is evaluated.
Any remaining WHERE clause predicates are evaluated.The predicates "cust_id = 2305240 and sort_key is not null" are applied last.
Similar Messages
-
CONNECT BY PRIOR USING MULTIPLE TABLES RETURNS AWKAWARD RESULTS.
CREATE TABLE "JAM"."FTVORGN2"
( "FTVORGN_COAS_CODE" VARCHAR2(1 CHAR) NOT NULL ENABLE,
"FTVORGN_ORGN_CODE" VARCHAR2(6 CHAR) NOT NULL ENABLE,
"FTVORGN_EFF_DATE" DATE NOT NULL ENABLE,
"FTVORGN_ACTIVITY_DATE" DATE NOT NULL ENABLE,
"FTVORGN_USER_ID" VARCHAR2(30 CHAR) NOT NULL ENABLE,
"FTVORGN_NCHG_DATE" DATE NOT NULL ENABLE,
"FTVORGN_TERM_DATE" DATE,
"FTVORGN_TITLE" VARCHAR2(35 CHAR) NOT NULL ENABLE,
"FTVORGN_STATUS_IND" VARCHAR2(1 CHAR),
"FTVORGN_ORGN_CODE_PRED" VARCHAR2(6 CHAR),
"FTVORGN_DATA_ENTRY_IND" VARCHAR2(1 CHAR) NOT NULL ENABLE,
"FTVORGN_VPDI_CODE" VARCHAR2(6 CHAR)
I have a table like the above.
I also have a table like the below.
CREATE TABLE "JAM"."FORUSOR"
( "FORUSOR_USER_ID_ENTERED" VARCHAR2(30 CHAR) NOT NULL ENABLE,
"FORUSOR_COAS_CODE" VARCHAR2(1 CHAR) NOT NULL ENABLE,
"FORUSOR_ORGN_CODE" VARCHAR2(6 CHAR) NOT NULL ENABLE,
"FORUSOR_ACCESS_IND" VARCHAR2(1 CHAR) NOT NULL ENABLE,
"FORUSOR_ACTIVITY_DATE" DATE NOT NULL ENABLE,
"FORUSOR_USER_ID" VARCHAR2(30 CHAR) NOT NULL ENABLE,
"FORUSOR_WBUD_ACCESS_IND" VARCHAR2(1 CHAR) NOT NULL ENABLE,
"FORUSOR_SURROGATE_ID" NUMBER(19,0),
"FORUSOR_VERSION" NUMBER(19,0),
"FORUSOR_DATA_ORIGIN" VARCHAR2(30 CHAR),
"FORUSOR_VPDI_CODE" VARCHAR2(6 CHAR)
REM INSERTING into FTVORGN2
SET DEFINE OFF;
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','01',to_date('01-OCT-88','DD-MON-RR'),to_date('19-MAR-97','DD-MON-RR'),'TRAIN01',to_date('31-DEC-99','DD-MON-RR'),null,'TOTAL UNIVERSITY','A',null,'N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','1006',to_date('22-SEP-14','DD-MON-RR'),to_date('22-SEP-14','DD-MON-RR'),'MJ35',to_date('31-DEC-99','DD-MON-RR'),null,'Provost','A','01','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','2027',to_date('01-OCT-97','DD-MON-RR'),to_date('01-OCT-97','DD-MON-RR'),'DARDARMT',to_date('31-DEC-99','DD-MON-RR'),null,'Sch of Biomed Engr, Sci Health Sys','A','1006','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','2028',to_date('28-FEB-01','DD-MON-RR'),to_date('28-FEB-01','DD-MON-RR'),'JMOORE',to_date('31-DEC-99','DD-MON-RR'),null,'Sch of Envr Science, Engr Policy','A','1006','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','5275',to_date('01-OCT-97','DD-MON-RR'),to_date('02-JUL-99','DD-MON-RR'),'JMOORE',to_date('31-DEC-99','DD-MON-RR'),null,'Administration','A','1006','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','5325',to_date('01-OCT-97','DD-MON-RR'),to_date('13-JAN-00','DD-MON-RR'),'JMOORE',to_date('31-DEC-99','DD-MON-RR'),null,'Enrollment & Career Management','A','1006','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','5350',to_date('01-OCT-97','DD-MON-RR'),to_date('02-JUL-99','DD-MON-RR'),'JMOORE',to_date('31-DEC-99','DD-MON-RR'),null,'Office of Education','A','1006','N',null);
Insert into FTVORGN2 (FTVORGN_COAS_CODE,FTVORGN_ORGN_CODE,FTVORGN_EFF_DATE,FTVORGN_ACTIVITY_DATE,FTVORGN_USER_ID,FTVORGN_NCHG_DATE,FTVORGN_TERM_DATE,FTVORGN_TITLE,FTVORGN_STATUS_IND,FTVORGN_ORGN_CODE_PRED,FTVORGN_DATA_ENTRY_IND,FTVORGN_VPDI_CODE) values ('D','5365',to_date('01-OCT-97','DD-MON-RR'),to_date('02-JUL-99','DD-MON-RR'),'JMOORE',to_date('31-DEC-99','DD-MON-RR'),null,'Library','A','1006','N',null);
REM INSERTING into FORUSOR
SET DEFINE OFF;
Insert into FORUSOR (FORUSOR_USER_ID_ENTERED,FORUSOR_COAS_CODE,FORUSOR_ORGN_CODE,FORUSOR_ACCESS_IND,FORUSOR_ACTIVITY_DATE,FORUSOR_USER_ID,FORUSOR_WBUD_ACCESS_IND,FORUSOR_SURROGATE_ID,FORUSOR_VERSION,FORUSOR_DATA_ORIGIN,FORUSOR_VPDI_CODE) values ('jam337','D','1006','B',to_date('01-AUG-12','DD-MON-RR'),'P','N',null,null,null,null);
Insert into FORUSOR (FORUSOR_USER_ID_ENTERED,FORUSOR_COAS_CODE,FORUSOR_ORGN_CODE,FORUSOR_ACCESS_IND,FORUSOR_ACTIVITY_DATE,FORUSOR_USER_ID,FORUSOR_WBUD_ACCESS_IND,FORUSOR_SURROGATE_ID,FORUSOR_VERSION,FORUSOR_DATA_ORIGIN,FORUSOR_VPDI_CODE) values ('jam337','D','1007','B',to_date('01-AUG-12','DD-MON-RR'),'P','N',null,null,null,null);
Insert into FORUSOR (FORUSOR_USER_ID_ENTERED,FORUSOR_COAS_CODE,FORUSOR_ORGN_CODE,FORUSOR_ACCESS_IND,FORUSOR_ACTIVITY_DATE,FORUSOR_USER_ID,FORUSOR_WBUD_ACCESS_IND,FORUSOR_SURROGATE_ID,FORUSOR_VERSION,FORUSOR_DATA_ORIGIN,FORUSOR_VPDI_CODE) values ('jam337','D','1011','B',to_date('01-AUG-12','DD-MON-RR'),'P','N',null,null,null,null);
Insert into FORUSOR (FORUSOR_USER_ID_ENTERED,FORUSOR_COAS_CODE,FORUSOR_ORGN_CODE,FORUSOR_ACCESS_IND,FORUSOR_ACTIVITY_DATE,FORUSOR_USER_ID,FORUSOR_WBUD_ACCESS_IND,FORUSOR_SURROGATE_ID,FORUSOR_VERSION,FORUSOR_DATA_ORIGIN,FORUSOR_VPDI_CODE) values ('jam337','D','1026','Q',to_date('30-JAN-08','DD-MON-RR'),'P','N',null,null,null,null);
Insert into FORUSOR (FORUSOR_USER_ID_ENTERED,FORUSOR_COAS_CODE,FORUSOR_ORGN_CODE,FORUSOR_ACCESS_IND,FORUSOR_ACTIVITY_DATE,FORUSOR_USER_ID,FORUSOR_WBUD_ACCESS_IND,FORUSOR_SURROGATE_ID,FORUSOR_VERSION,FORUSOR_DATA_ORIGIN,FORUSOR_VPDI_CODE) values ('jam337','D','1100','Q',to_date('30-JAN-08','DD-MON-RR'),'P','N',null,null,null,null);
the ftvorgn table is hierachical in nature, where the forusor table is not . The FORUSOR table holds the name and a hiearchy node from the FTVORGN TABLE within it.
I have spent several hours trying to get a query to work. I just don't see what my error is? if you follow the trail thus far you will notice that the FORUSOR table contains a value of '1006' in the FORUSOR_ORGN_CODE column. However everytime I run this query i get duplicate rows in return.
SELECT FTVORGN_ORGN_CODE,
FTVORGN_DATA_ENTRY_IND,
FTVORGN_TITLE,
FTVORGN_STATUS_IND,
FTVORGN_ORGN_CODE_NSF,
FTVORGN_HIERARCHY_TABLE_IND,
LEVEL, FTVORGN_ORGN_CODE_PRED
FROM FTVORGN2, FORUSOR
WHERE FORUSOR.FORUSOR_USER_ID_ENTERED = 'jam337'
CONNECT BY PRIOR FTVORGN_ORGN_CODE = FTVORGN_ORGN_CODE_PRED
AND PRIOR FTVORGN_COAS_CODE = FTVORGN_COAS_CODE
AND FTVORGN_EFF_DATE <= TO_DATE(sysdate)
AND FTVORGN_NCHG_DATE > TO_DATE(sysdate)
START WITH FTVORGN_ORGN_CODE = FORUSOR_ORGN_CODE
AND FTVORGN_COAS_CODE = 'D'
AND FTVORGN_EFF_DATE <= TO_DATE(sysdate)
AND FTVORGN_NCHG_DATE > TO_DATE(sysdate);
I't trying to basically get all the predecessor notes for everynote on FORUSOR but i keep ending up with duplicate rows.
I should end up with something similar to this.
sorry for the format of the results I'm not very good at formatting.
"FTVORGN_ORGN_CODE"
"FTVORGN_DATA_ENTRY_IND"
"FTVORGN_STATUS_IND"
"LEVEL"
"FTVORGN_ORGN_CODE_PRED"
"1006"
"N"
"A"
"1"
"01"
"2027"
"N"
"A"
"2"
"1006"
"2028"
"N"
"A"
"2"
"1006"
"5275"
"N"
"A"
"2"
"1006"
"5325"
"N"
"A"
"2"
"1006"
"5350"
"N"
"A"
"2"
"1006"
"5365"
"N"
"A"
"2"
"1006"
on column FORUSOR_ORGN_CODE in the FORUSOR table there is a node value that corresponds to a value on FTVORGN. However , that value could have a FTVORGN_ORGN_CODE_PRED which basically says I'm reporting to this value.
if I basically run this query for a node you can see the hierachy.
SELECT FTVORGN_ORGN_CODE,
FTVORGN_DATA_ENTRY_IND,
FTVORGN_STATUS_IND,
LEVEL, FTVORGN_ORGN_CODE_PRED
FROM FTVORGN2
CONNECT BY PRIOR FTVORGN_ORGN_CODE = FTVORGN_ORGN_CODE_PRED
AND PRIOR FTVORGN_COAS_CODE = FTVORGN_COAS_CODE
AND FTVORGN_EFF_DATE <= TO_DATE(sysdate)
AND FTVORGN_NCHG_DATE > TO_DATE(sysdate)
START WITH FTVORGN_ORGN_CODE = '1006'
AND FTVORGN_COAS_CODE = 'D'
AND FTVORGN_EFF_DATE <= TO_DATE(sysdate)
AND FTVORGN_NCHG_DATE > TO_DATE(sysdate);
I now need to pass the orgn code from forusor to this query to get all the ftvorgn_orgn_code that this user technically has reporting to him on FORUSOR.
so for example user jma337 has org
1006 in forusor
when i run the query i should get
jma337 2027
jma337 2028
jma337 5275 etc.
Reason in because these are all predecessors of 1006 which in this case would essentially be our level 1.
I need to do this all the FORUSOR_ORGN_CODE this user has recorded to him on FORUSOR.Switching to four digit years (to make the query work)
with
ftvorgn2 as
(select 'D' ftvorgn_coas_code,
'01' ftvorgn_orgn_code,
to_date('01-OCT-1988','DD-MON-YYYY') ftvorgn_eff_date,
to_date('19-MAR-1997','DD-MON-YYYY') ftvorgn_activity_date,
'TRAIN01' ftvorgn_user_id,
to_date('31-DEC-2099','DD-MON-YYYY') ftvorgn_nchg_date,
null ftvorgn_term_date,
'TOTAL UNIVERSITY' ftvorgn_title,
'A' ftvorgn_status_ind,
null ftvorgn_orgn_code_pred,
'N' ftvorgn_data_entry_ind,
null ftvorgn_vpdi_code
from dual
union all
select 'D','1006',to_date('22-SEP-2014','DD-MON-YYYY'),to_date('22-SEP-2014','DD-MON-YYYY'),'MJ35',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Provost','A','01','N',null from dual union all
select 'D','2027',to_date('01-OCT-1997','DD-MON-YYYY'),to_date('01-OCT-1997','DD-MON-YYYY'),'DARDARMT',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Sch of Biomed Engr, Sci Health Sys','A','1006','N',null from dual union all
select 'D','2028',to_date('28-FEB-2001','DD-MON-YYYY'),to_date('28-FEB-2001','DD-MON-YYYY'),'JMOORE',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Sch of Envr Science, Engr Policy','A','1006','N',null from dual union all
select 'D','5275',to_date('01-OCT-1997','DD-MON-YYYY'),to_date('02-JUL-1999','DD-MON-YYYY'),'JMOORE',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Administration','A','1006','N',null from dual union all
select 'D','5325',to_date('01-OCT-1997','DD-MON-YYYY'),to_date('13-JAN-2000','DD-MON-YYYY'),'JMOORE',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Enrollment & Career Management','A','1006','N',null from dual union all
select 'D','5350',to_date('01-OCT-1997','DD-MON-YYYY'),to_date('02-JUL-1999','DD-MON-YYYY'),'JMOORE',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Office of Education','A','1006','N',null from dual union all
select 'D','5365',to_date('01-OCT-1997','DD-MON-YYYY'),to_date('02-JUL-1999','DD-MON-YYYY'),'JMOORE',to_date('31-DEC-2099','DD-MON-YYYY'),null,'Library','A','1006','N',null from dual
forusor as
(select 'jam337' forusor_user_id_entered,
'D' forusor_coas_code,
'1006' forusor_orgn_code,
'B' forusor_access_ind,
to_date('01-AUG-12','DD-MON-RR') forusor_activity_date,
'P' forusor_user_id,
'N' forusor_wbud_access_ind,
null forusor_surrogate_id,
null forusor_version,
null forusor_data_origin,
null forusor_vpdi_code
from dual
union all
select 'jam337','D','1007','B',to_date('01-AUG-2012','DD-MON-YYYY'),'P','N',null,null,null,null from dual union all
select 'jam337','D','1011','B',to_date('01-AUG-2012','DD-MON-YYYY'),'P','N',null,null,null,null from dual union all
select 'jam337','D','1026','Q',to_date('30-JAN-2008','DD-MON-YYYY'),'P','N',null,null,null,null from dual union all
select 'jam337','D','1100','Q',to_date('30-JAN-2008','DD-MON-YYYY'),'P','N',null,null,null,null from dual
select ftvorgn_orgn_code,
ftvorgn_data_entry_ind,
ftvorgn_title,
ftvorgn_status_ind,
-- ftvorgn_orgn_code_nsf,
-- ftvorgn_hierarchy_table_ind,
level,
ftvorgn_orgn_code_pred
from ftvorgn2
start with ftvorgn_orgn_code in (select forusor_orgn_code
from forusor
where forusor_user_id_entered = 'jam337'
-- and forusor_coas_code = 'D'
connect by prior ftvorgn_orgn_code = ftvorgn_orgn_code_pred
and ftvorgn_eff_date <= sysdate
and ftvorgn_nchg_date > sysdate
FTVORGN_ORGN_CODE
FTVORGN_DATA_ENTRY_IND
FTVORGN_TITLE
FTVORGN_STATUS_IND
LEVEL
FTVORGN_ORGN_CODE_PRED
1006
N
Provost
A
1
01
2027
N
Sch of Biomed Engr, Sci Health Sys
A
2
1006
2028
N
Sch of Envr Science, Engr Policy
A
2
1006
5275
N
Administration
A
2
1006
5325
N
Enrollment & Career Management
A
2
1006
5350
N
Office of Education
A
2
1006
5365
N
Library
A
2
1006
Regards
Etbin -
CONNECT BY PRIOR - ORDERING ROWS
Hi all,
I am working on database server - oracle 10g enterprise edition R2,
forms - Oracle forms 10G -Version 10.1.2.0.2 on windows 2000 professional.
I have a table ACCOUNT_GROUP_MASTER with the following structure.
DESC ACCOUNT_GROUP_MASTER
Name Null? Type
ACCOUNT_GROUP_CODE NOT NULL NCHAR(6)
ACCOUNT_GROUP_NAME NOT NULL NVARCHAR2(40)
ACCOUNT_GROUP_TYPE CHAR(1)
GROUP_DISP_ORDER NUMBER(3)
MAIN_GROUP_CODE NCHAR(6)
Account_group_code is the primary key
and Main_group_code is the foreign key(self referencing) referring Account_group_code of the same table.
My query and the returned data are given below.
SELECT
level, account_group_code act, GROUP_DISP_ORDER ord
FROM ACCOUNT_GROUP_MASTER
CONNECT BY PRIOR ACCOUNT_GROUP_CODE=MAIN_GROUP_CODE
START WITH main_GROUP_code is null
order by account_group_code
LEVEL ACT ORD
1 4000 1
2 4100
2 4200 3
2 4300 1
1 2000 2
2 2100 2
2 2200 1
My task is to sort the output in the order of
First sort column is "level" and within the "level", data should be sorted by the
group_disp_order column.
That is the above output should come as given below.
LEVEL ACT ORD
1 4000 1
2 4100
2 4300 1
2 4200 3
1 2000 2
2 2200 1
2 2100 2
Can anybody help me please.
Thanks in advance.
Regards
MohanHi All
The solution to the above problem is solved by the following query.
SELECT 1,level, account_group_code|| account_group_NAME,NULL,
account_group_code
FROM ACCOUNT_GROUP_MASTER
CONNECT BY PRIOR ACCOUNT_GROUP_CODE=MAIN_GROUP_CODE
START WITH main_GROUP_code is null
order siblings by group_disp_order
Regards
Mohan -
Join two Connect By Prior Start With trees and return only common records?
Oracle 10g Release 2 (10.2)
I have two tables that have tree structured data. The results, when running the queries individually are correct, however I need to join tree one to tree two in order to obtain only the common records between them.
-- Tree one
SELECT ip_entity_name, entity_code, hier_level, entity_parent
FROM ip_hierarchy
WHERE hier_level >= 3
CONNECT BY PRIOR entity_code = entity_parent
START WITH entity_code = 'MEWWD';
-- Tree two
SELECT ip_entity_name, entity_code, hier_level, entity_parent
FROM ipt_hierarchy
WHERE hier_level >= 3
CONNECT BY PRIOR entity_code = entity_parent
START WITH entity_code = 'IPNAM';
As I understand, joins may not work with CONNECT BY/START WITH queries?
Is a WITH clause an option?
If at all possible, I don't want to put one select in a View database object and join against the other query.
Thanks.Hi JTP51,
You can use WITH clause or sub-query by using in-line view, without creating any view object in database.
for example
SELECT A.IP_ENTITY_NAME, A.ENTITY_CODE, ....
FROM (SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
FROM IP_HIERARCHY
WHERE HIER_LEVEL >= 3
CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
START WITH ENTITY_CODE = 'MEWWD') A,
(SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
FROM IPT_HIERARCHY
WHERE HIER_LEVEL >= 3
CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
START WITH ENTITY_CODE = 'IPNAM') B
WHERE A. ENTITY_CODE = B. ENTITY_CODE
AND ....Best regards,
Zhxiang
Edited by: zhxiangxie on Feb 2, 2010 5:35 PM -
Is there a way in Oracle to return multiple rows as a single string?
Hi gurus,
I just got help from your guys fixing my dynamic sql problem. What I am doing in that function is to return a single string from multiple rows and I use it in the select statement. It works fine once the problem was solved. But is there any way in Oracle to do this in the select statement only? I have a table that stores incidents (incident_id is the PK) and another table that stores the people that are involved in an incident.
Incident_table
(incident_id number PK);
Incident_people_table
(incident_id number PK/FK,
person_id number PK);
Now in a report, I need to return the multiple rows of the Incident_People_table as a single string separated by a comma, for example, 'Ben, John, Mark'. I asked the SQL Server DBA about this and he told me he can do that in SQL Server by using a variable in the sql statement and SQL Server will auomatically iterate the rows and concatenate the result (I have not seen his actual work). Is there a similar way in Oracle? I have seen some examples here for some similar requests using the sys_connect_by_path, but I wonder if it is feasible in a report sql that is already rather complex. Or should I just stick to my simpler funcion?
Thanks.
BenHi,
May be, this example will help you.
SQL> CREATE TABLE Incident_Table(
2 incident_id number
3 );
Table created.
SQL> CREATE TABLE Person_Table(
2 person_id number,
3 person_name VARCHAR2(200)
4 );
Table created.
SQL> CREATE TABLE Incident_People_Table(
2 incident_id number,
3 person_id number
4 );
Table created.
SQL> SELECT * FROM Incident_Table;
INCIDENT_ID
1
2
SQL> SELECT * FROM Person_Table;
PERSON_ID PERSON_NAME
1 John
2 Mark
3 Ben
4 Sam
SQL> SELECT * FROM Incident_People_Table;
INCIDENT_ID PERSON_ID
1 1
1 2
1 3
2 1
2 2
2 4
6 rows selected.
SQL> SELECT IT.*,
2 (
3 WITH People_Order AS (
4 SELECT IPT.incident_id, person_id, PT.person_name,
5 ROW_NUMBER() OVER (PARTITION BY IPT.incident_id ORDER BY PT.person_name) AS Order_Num,
6 COUNT(*) OVER (PARTITION BY IPT.incident_id) AS incident_people_cnt
7 FROM Incident_People_Table IPT
8 JOIN Person_Table PT USING(person_id)
9 )
10 SELECT SUBSTR(SYS_CONNECT_BY_PATH(PO.person_name, ', '), 3) AS incident_people_list
11 FROM (SELECT * FROM People_Order PO WHERE PO.incident_id = IT.incident_id) PO
12 WHERE PO.incident_people_cnt = LEVEL
13 START WITH PO.Order_Num = 1
14 CONNECT BY PRIOR PO.Order_Num = PO.Order_Num - 1
15 ) AS incident_people_list
16 FROM Incident_Table IT
17 ;
INCIDENT_ID INCIDENT_PEOPLE_LIST
1 Ben, John, Mark
2 John, Mark, SamRegards,
Dima -
DECODE is not working in WHERE clause when subquery returns more rows
Hi Gurus,
I want to write a query on CCENTERS table(Script given below) and expect the following result:
1. When I pass a value of 0 for ID, It returns all the rows given in the table.
2. When I pass a value other than 0, It returns the row for the given value as well as all its child records.
CCENTER has parent-child relationship in ID and BASE column. I am using a query with DECODE function. but DECODE function in WHERE clause is not capable of handling sub-query with multiple rows.
VARIABLE ParaCCenter NUMBER
BEGIN
:paraccenter:=0;
END;
CREATE TABLE ccenters
(id NUMBER,
name VARCHAR2(20),
base number);
INSERT INTO ccenters VALUES(1,'NUST',null);
INSERT INTO ccenters VALUES(2,'SEECS',1);
INSERT INTO ccenters VALUES(3,'NBS',1);
commit;
SELECT * FROM ccenters
WHERE id IN DECODE(:ParaCCenter, 0, id,
(SELECT id FROM ccenters
START WITH base=:ParaCCenter
CONNECT BY PRIOR id = base
UNION
SELECT :ParaCCenter FROM dual
BEGIN
:paraCCenter:=1;
END;
SELECT * FROM ccenters
WHERE id IN DECODE(:ParaCCenter, 0, id,
(SELECT id FROM ccenters
START WITH base=:ParaCCenter
CONNECT BY PRIOR id = base
UNION
SELECT :ParaCCenter FROM dual))
The result is
(SELECT id FROM ccenters
ERROR at line 3:
ORA-01427: single-row subquery returns more than one row
How this query can be rewritten for the given functionality. Any response will be highly appreciated.
ThanksAnd if you want to use DECODE:
SQL> BEGIN
2 :paraccenter:=0;
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> select *
2 from ccenters
3 where :paraccenter = decode(:paraccenter,0,0,id)
4 /
ID NAME BASE
1 NUST
2 SEECS 1
3 NBS 1
SQL> BEGIN
2 :paraccenter:=2;
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> select *
2 from ccenters
3 where :paraccenter = decode(:paraccenter,0,0,id)
4 /
ID NAME BASE
2 SEECS 1
SQL> SY. -
Connect by prior by speific order problem.
Oracle: 10.2.0.4
I have a table containing events backup.
i want to list the hierarchy within that backup oreder by the time_stamp for all levels.
create table BCK_EVENTS
bck_backup_id NUMBER(9) default 0 not null,
event_id NUMBER(15) default 0 not null,
event_name NVARCHAR2(100) default ' ' not null
time_stamp NUMBER(9) default 0 not null,
parent_event NUMBER(15) default 0 not null,
add constraint BCK_EVENTS_PK primary key (BCK_EVENT_ID, EVENT_ID); // event_id is not unique can be under one or more backup id'sthis is not a tree with one root, there is more than one event in the root level (level 1).
example:
Event Name Time level <- time is numeric but for easier reading.
*Event A 10:00 1
*Event C 10:30 2
*Event B 11:17 3
*Event H 12:10 1
*Event J 12:10 2
*Event M 12:21 2
*Event Z 15:33 1
*Event R 16:56 2
*Event M 16:57 3
*Event G 20:20 2What i tried was :
select lpad( '*', level*2 ) || event_id,event_name,time_stamp,parent_event,level from bck_events
where bck_event_id=100031
start with parent_event is null
connect by prior event_id = parent_eventand there are two problems with it.
1. it's not ordered even when i added an Index (parent_event,time_stamp) and try to hint it.
2. it returns loads of multiple rows.
hope it's clear enough. I thank for any help.
Edited by: 973065 on Nov 25, 2012 8:04 AM
Edited by: 973065 on Nov 25, 2012 9:23 AM
Edited by: 973065 on Nov 25, 2012 9:29 AM
Edited by: 973065 on Nov 25, 2012 9:31 AMHi,
973065 wrote:
Oracle: 10.2
I have a table containing events backup.
i want to list the hierarchy within that backup oreder by the time_stamp for all levels.
create table BCK_EVENTS
bck_backup_id NUMBER(9) default 0 not null,
event_id NUMBER(15) default 0 not null,
event_name NVARCHAR2(100) default ' ' not null
time_stamp NUMBER(9) default 0 not null,
parent_event NUMBER(15) default 0 not null,
Thanks for posting the version number and the CREATE TABLE statement. Don't forget to post INSERT statements for your sample data.
add constraint BCK_EVENTS_PK primary key (BCK_EVENT_ID, EVENT_ID); // event_id is not unique can be under one or more backup id's
this is not a tree with one root, there is more than one event in the root level (level 1).Is it a forest, that is, a set of trees?
example:
Event Name Time level <- time is numeric but for easier reading.
*Event A 10:00 1
*Event C 10:30 2
*Event B 11:17 3
*Event H 12:10 1
*Event J 12:10 2
*Event M 12:21 2
*Event Z 15:33 1
*Event R 16:56 2
*Event M 16:57 3
*Event G 20:20 2
That seems to be a forest, that is, every row has 0 or 1 parent, and no row is its own ancestor.
What i tried was :
select lpad( '*', level*2 ) || event_id,event_name,time_stamp,parent_event,level from bck_events
where bck_event_id=100031
start with parent_event is null
connect by prior event_id = parent_event
and there are two problems with it.
1. it's not ordered even when i added an Index (parent_event,time_stamp) and try to hint it.Depending on your data, you may just need to add
ORDER SIBLINGS BY time_stampat the end, after the CONNECT BY clause.
If you need rows sorted by time_stamp under their roots, but otherwise without regard to the hierarchy, then use CONNECT_BY_ROOT.
2. it returns loads of multiple rows.Again, it depends on your data. I'll bet you need something more in the CONNECT BY clause, but I can't tell what without some sample data and an exxplanation of how you gett the results you posted from that data. The fact that bck_event_id is part of the primary key makes me suspect that maybe bck_event_id needs to be somewhere in the CONNECT BY clause, but that's just a wild guess.
hope it's clear enough. I thank for any help.As mentioned before, see the forum FAQ {message:id=9360002} -
Slow connect by prior ... start with subquery in 9i
Has anyone come across a performance problem (compared to 8i) when using hierarchical queries where the START WITH list is generated by a subquery? The culprit seems to be an extra visit to the subquery block as part of the CONNECT BY WITH FILTERING operation.
For example, take a simple tree structure:
CREATE TABLE tree
id NUMBER,
parentid NUMBER
CONSTRAINT tree_pk PRIMARY KEY (id)
...and a subquery - here just a table called sample with a subset of the ids from the tree table:
CREATE TABLE sample
id NUMBER,
CONSTRAINT sample_pk PRIMARY KEY (id)
...with which to drive the start points of the treewalk:
SELECT parentid, id, label
FROM tree
CONNECT BY PRIOR parentid = id
START WITH id IN
SELECT id FROM SAMPLE
With the tables populated and analyzed, I get this from 8i:
Execution Plan
.0......SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=19)
.1....0...CONNECT BY
.2....1.....NESTED LOOPS (Cost=1 Card=1280 Bytes=10240)
.3....2.......INDEX (FAST FULL SCAN) OF 'ID_PK' (UNIQUE) (Cost=1 Card=1280 Bytes=5120)
.4....2.......INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE)
.5....1.....TABLE ACCESS (BY USER ROWID) OF 'TREE'
.6....1.....TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (Cost=2 Card=1 Bytes=19)
.7....6.......INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE) (Cost=1 Card=1)
Statistics
.....0..recursive calls
.....4..db block gets
.15687..consistent gets
....59..physical reads
.....0..redo size
223313..bytes sent via SQL*Net to client
.38276..bytes received via SQL*Net from client
...343..SQL*Net roundtrips to/from client
.....3..sorts (memory)
.....0..sorts (disk)
..5120..rows processed
and this is 9i:
Execution Plan
.0......SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=19)
.1....0...CONNECT BY (WITH FILTERING)
.2....1.....NESTED LOOPS
.3....2.......NESTED LOOPS (Cost=2 Card=1280 Bytes=10240)
.4....3.........INDEX (FAST FULL SCAN) OF 'ID_PK' (UNIQUE) (Cost=2 Card=1280 Bytes=5120)
.5....3.........INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE)
.6....2.......TABLE ACCESS (BY USER ROWID) OF 'TREE'
.7....1.....NESTED LOOPS
.8....7.......BUFFER (SORT)
.9....8.........CONNECT BY PUMP
10....7.......TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (Cost=2 Card=1 Bytes=19)
11...10.........INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE) (Cost=1 Card=20480)
12....1.....INDEX (UNIQUE SCAN) OF 'SAMPLE_PK' (UNIQUE) (Cost=1 Card=1 Bytes=4)
Statistics
.....1..recursive calls
.....1..db block gets
.20525..consistent gets
....72..physical reads
...120..redo size
224681..bytes sent via SQL*Net to client
.38281..bytes received via SQL*Net from client
...343..SQL*Net roundtrips to/from client
.....9..sorts (memory)
.....0..sorts (disk)
..5120..rows processed
..so, about another 5000 logical reads, corresponding to the extra access of the sample table at the bottom of the query plan. So instead of just visiting the START WITH subquery once, to kick off the treewalk, I seem to be revisiting it for every row returned. Not too bad if that happens to be a unique index scan as here but that's not always the case.
I know I've got new options for re-writing this as a join under 9i, I'm just curious about those extra lookups and why they're necessary.
Cheers - AndrewThere is undocumented parameter in Oracle 9i "_old_connect_by_enabled"
which controls the behavoiur of hierarchy queries in 9i and above:
You can try to return to 8i behaviour using it:
SQL> SELECT parentid, id
2 FROM tree
3 CONNECT BY PRIOR parentid = id
4 START WITH id IN
5 (
6 SELECT id FROM SAMPLE
7 )
8 /
Execution Plan
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=26)
1 0 CONNECT BY (WITH FILTERING)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE)
3 2 NESTED LOOPS (Cost=2 Card=1 Bytes=26)
4 3 TABLE ACCESS (FULL) OF 'SAMPLE' (TABLE) (Cost=2 Card
=1 Bytes=13)
5 3 INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (C
ost=0 Card=1 Bytes=13)
6 1 NESTED LOOPS
7 6 BUFFER (SORT)
8 7 CONNECT BY PUMP
9 6 TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE) (Cost=
1 Card=1 Bytes=26)
10 9 INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (C
ost=1 Card=1)
11 1 TABLE ACCESS (FULL) OF 'TREE' (TABLE) (Cost=1 Card=1 Byt
es=26)
12 1 INDEX (UNIQUE SCAN) OF 'SAMPLE_PK' (INDEX (UNIQUE)) (Cos
t=1 Card=1 Bytes=13)
SQL> alter session set "_old_connect_by_enabled" = TRUE;
Session altered.
SQL> SELECT parentid, id
2 FROM tree
3 CONNECT BY PRIOR parentid = id
4 START WITH id IN
5 (
6 SELECT id FROM SAMPLE
7 )
8 /
Execution Plan
0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=26)
1 0 CONNECT BY
2 1 NESTED LOOPS (Cost=2 Card=1 Bytes=26)
3 2 TABLE ACCESS (FULL) OF 'SAMPLE' (TABLE) (Cost=2 Card=1
Bytes=13)
4 2 INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (Cos
t=0 Card=1 Bytes=13)
5 1 TABLE ACCESS (BY USER ROWID) OF 'TREE' (TABLE)
6 1 TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE) (Cost=1
Card=1 Bytes=26)
7 6 INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (Cos
t=1 Card=1)
Rgds. -
Get error when CONNECT BY PRIOR used by where
Hi
I get "No more data to read from socket" error when the result of CONNECT BY PRIOR used after where, is there anybody encounter this error?
example SQL:
select
from table_A
where exists
(select 1 from table_b
START WITH table_b.col1 = 'value'
CONNECT BY PRIOR table_b.col1 = table_b.col2)
The sql select 1 from table_b START WITH table_b.col1 = 'value' CONNECT BY PRIOR table_b.col1 = table_b.col2 can return 2 row correct, but the whole sql does not work.Hi! Rahul,
Thank you for your reply first. Your method doesn't work in my case. Can you tell me the steps of creating a new layout for added records and draft documents. I have created a quotation layout which work with added records only, the steps has been show below and please comments, thanks.
1. In Crystal Report > new blank report > create new connection > Choose "SAP Business One" > Select OQUT under "B1 Tables".
2. Insert "CardName" field to report > Create DocKey@ parameter and set it equal to DocEntry in select expert record function
3. Click Add-ins > SAP Business One > Save > Choose company database and input manager password.
Regards,
Ivan -
Complex connect by prior query
I need SQL(for hierarchical tree) for a function which accepts node as input parameter and returns ref cursor.
Following is a sample tree:
1
--2.1
----3.1
------4.1
--------5.1
----------6.1
----------6.2
----3.2
------4.2
--------5.2
--2.2
----3.2
------4.2
--------5.2
----3.3
----3.4
------4.1
--------5.1
----------6.1
----------6.2
1 is at the root level and 2.1 & 2.2 are immediate children and so on.
The output tree should be all related parents and children of the passed node.
e.g:
If the input is 4.1, the output tree will be:
1
--2.1
----3.1
------4.1
--------5.1
----------6.1
----------6.2
--2.2
----3.4
------4.1
--------5.1
----------6.1
----------6.2
If the input is 4.2, the output tree will be:
1
--2.1
----3.2
------4.2
--------5.2
--2.2
----3.2
------4.2
--------5.2
The complex part, I guess, is to remove unwanted(not related) branches from the tree.
Following is the representation of the table RELATIONSHIP
ID PARENT CHILD
1-------1-------2.1
2-------1-------2.2
3-------2.1-----3.1
4-------2.1-----3.2
5-------2.2-----3.2
6-------2.2-----3.3
7-------2.2-----3.4
8-------3.1-----4.1
9-------3.2-----4.2
10------3.4-----4.1
11------4.1-----5.1
12------4.2-----5.2
13------5.1-----6.1
14------5.1-----6.2
Pls. help me out to form this CONNECT BY PRIOR query.
Thanks in advance.make sure you include 2 things in your queries.
# the row number
# the level
for traversing up the tree set
level = 0 - level and
row_number = 0 - row_number.
you than can then do an order by row_number if you union the two queries
for example:
============
select tbl.child,
tbl.parent,
level lvl,
rownum rn
from some_table tbl
start with tbl.parent = 4.1
connect by prior tbl.child = tbl.parent
union
select tbl.child,
tbl.parent,
0 - level lvl,
0 - rownum rn
from some_table tbl
start with tbl.child = 4.1
connect by prior tbl.parent = tbl.child
order by rn asc -
Connect By Prior - Performance and Missing Parent
I have to say right off the top that I'm not a SQL expert by any means so please be gentle. :)
I have a query that runs through a Bill Of Materials that works except for two things:
1. It is horribly slow - 60-90 seconds to return under 300 rows.
2. It doesn't show the parent node.
I'm looking into indexes now, so I'm not sure if there's an issue there or not. As far as #2 goes, there are two tables that are involved: BOM_STRUCTURES_B and BOM_COMPONENTS_B. Every item below the parent node has a BOM_COMPONENTS_B record. If a BOM_COMPONENT is a parent to other components, there is a BOM_STRUCTURES_B record for that. (In other words, everything that is a parent has a BOM_STRUCTURES_B record, and all the children have a BOM_COMPONENTS_B record that point to the parent - BOM_STRUCTURES_B). The only exception to this is the parent node, which only has a BOM_STRUCTURES_B record (it is NOT a child, so there is no BOM_COMPONENTS_B record). I've added a "UNION" to the bottom of the script below, but it changes my sort order completely.
Here's my script:
select bbm.assembly_item_id,
bic.component_item_id Component ,
msi.segment1 Name,
msi.description Description,
bic.component_quantity Quantity,
lpad( ' ', level*2 ) || level MyLevel
from bom_structures_b bbm
,bom_components_b bic
, mtl_system_items msi
where bbm.bill_Sequence_id = bic.bill_sequence_id
and msi.inventory_item_id = bic.component_item_id
and msi.organization_id = bbm.organization_id
start with bbm.assembly_item_id = 271962
and bbm.organization_id = 85
connect by prior bic.component_item_id = bbm.assembly_item_id;
I've hard-coded "start with bbm.assembly_item_id = 271962", as it is the root node of a tree (BOM).
Here's my structure, with extra fields clipped out:
DBMS_METADATA.GET_DDL('TABLE','BOM_STRUCTURES_B','BOM')
CREATE TABLE "BOM"."BOM_STRUCTURES_B"
( "ASSEMBLY_ITEM_ID" NUMBER,
"ORGANIZATION_ID" NUMBER NOT NULL ENABLE,
"COMMON_BILL_SEQUENCE_ID" NUMBER NOT NULL ENABLE,
) PCTFREE 20 PCTUSED 80 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
DBMS_METADATA.GET_DDL('TABLE','BOM_COMPONENTS_B','BOM')
CREATE TABLE "BOM"."BOM_COMPONENTS_B"
("COMPONENT_ITEM_ID" NUMBER,
"BILL_SEQUENCE_ID" NUMBER NOT NULL ENABLE,
"PARENT_BILL_SEQ_ID" NUMBER,
) PCTFREE 35 PCTUSED 50 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
DBMS_METADATA.GET_DDL('TABLE','MTL_SYSTEM_ITEMS_B','INV')
CREATE TABLE "INV"."MTL_SYSTEM_ITEMS_B"
( "INVENTORY_ITEM_ID" NUMBER NOT NULL ENABLE,
"ORGANIZATION_ID" NUMBER NOT NULL ENABLE,
"DESCRIPTION" VARCHAR2(240),
) PCTFREE 10 PCTUSED 70 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
The relationship between the tables is:
A BOM_STRUCTURES_B has many BOM_COMPONENTS_B where BOM_COMPONENTS_B.PARENT_BILL_SEQ_ID = BOM_STRUCTURES_B.BILL_SEQUENCE_ID. Both BOM_STRUCTURES_B.ASSEMBLY_ITEM_ID and BOM_COMPONENTS_B.COMPONENT_ITEM_ID are related to a single MTL_SYSTEM_ITEMS_B.INVENTORY_ITEM_ID.
Thanks to anyone who can help with this horrible problem I've been fighting with for much too long! :)
Thank you!
SteveDue to an error in the otn forums (*), this got posted to the wrong forum, sorry for that, I'll repost in the correct one.
*) For the forum admins: I was browsing the SQL/PLSQL forum, clicked on 'new message', got the login prompt, logged in, and apparently this got me to the application server forum for some reason. -
Hi
I have a situation where in my main query's where clause I have to use like ('% <value returned from query2>%'). However, my query2 can return multiple rows.
It is something like this:
Select .....
from table1 t1
where path like ('%<query2>%').
Path can have multiple values - it is just representing a parent child relationship like 1/2/3. 1 is a parent of 2. 2 is a parnt of 3 and so on. What I get from query2 could be either of these. So I have to use like and not in. How may I achieve this?select lvl,
Path
from (select distinct level as lvl,
sys_connect_by_path(parent,'/') Path
from table1 t1
connect by prior child = parent)
where instr(path,((select parent --+
from (select parent, sm, rank() over (order by sm desc) r |
from (SELECT parent, SUM(CT1) as sm |
FROM ((select parent,count(child) ct1 |
from table1 t1 |
where group by parent |
-- end level 1) |
UNION ALL |
(select parent, count(child) ct2 | try to move this sub-query
from table1 t1 | at the FROM clause
where child in --first level |
(select parent |
from (select distinct parent,count(child) ct1 |
from table1 t1 |
where group by parent) q1)-- end level 1 |
group by parent))--MAIN SEL |
GROUP BY parent)) |
where r =1))) > 0--end instr --+
and lvl = 1
you may try to move sub-queries in your WHERE clause to the FROM clause.
Message was edited by:
Warren Tolentino
justin has the same idea :D -
Bug Report: ResultSet.isLast() returns false when queries return zero rows
When calling the method isLast() on a resultset that contains zero (0) rows, false is returned. If a resultset contains no rows, isLast() should return true because returning false would indicate that there are more rows to be retrieved.
Try the following Java source:
import java.io.*;
import java.sql.*;
import java.util.*;
import oracle.jdbc.driver.*;
public class Test2 {
public static void main (String [] args) throws Exception {
Connection conn = null;
String jdbcURL = "jdbc:oracle:thin:@" +
"(DESCRIPTION=(ADDRESS=(HOST=<host computer>)"+
"(PROTOCOL=tcp)(PORT=<DB port number>))"+
"(CONNECT_DATA=(SID=<Oracle DB instance>)))";
String userId = "userid";
String password = "password";
try{
// Load the Oracle JDBC Driver and register it.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// *** The following statement creates a database connection object
// using the DriverManager.getConnection method. The first parameter is
// the database URL which is constructed based on the connection parameters
// specified in ConnectionParams.java.
// The URL syntax is as follows:
// "jdbc:oracle:<driver>:@<db connection string>"
// <driver>, can be 'thin' or 'oci8'
// <db connect string>, is a Net8 name-value, denoting the TNSNAMES entry
conn = DriverManager.getConnection(jdbcURL, userId, password);
} catch(SQLException ex){ //Trap SQL errors
// catch error
//conn = new OracleDriver().defaultConnection(); // Connect to Oracle 8i (8.1.7), use Oracle thin client.
PreparedStatement ps = conn.prepareStatement("select 'a' from dual where ? = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Use any query that will return zero rows.
ps.setInt(1, 1); // Set the params so that the query returns 0 rows.
ps.setInt(2, 2);
ResultSet rs = ps.executeQuery();
System.out.println("1. Last here? " + rs.isLast());
while (rs.next()) {
// do whatever
System.out.println("2. Last here? " + rs.isLast());
ps.close();
rs.close();
EXPECTED RESULT -
1. Last here? true
2. Last here? true
ACTUAL RESULT -
1. Last here? false
2. Last here? false
This happens to me on Oracle 9.2.0.1.0.387561,
For your information, I discovered this problem from
running a query that did access an actual DB table.
Try it and let me know.I did say I was only guessing, and yes, I did try it (after I posted my reply, and before I read yours). And I did check the query plan for the queries I tried -- to verify that they were actually doing some database "gets".
In any case, the usual way that I determine whether a "ResultSet" is empty is when the very first invocation of method "next()" returns 'false'. Is that not sufficient for you?
Good Luck,
Avi. -
SQL with connect by prior running for a long time
Hi,
We are using Oracle 10g. Below is a cursor sql which is having performance issues. The pAccountid is being passed from the output of a different cursor. But this cursor sql is running for a long time. Could you please help me in tuning this sql. I believe the subquery with connect by prior is causing the trouble.
The TRXNS is a huge table which is not partitioned. The query is forced to use the index on the accountid of the TRXNS table.
The accountlink table has 20,000 records and the TRXNStrack table has 10,000 records in total.
This sql executes for 200,000 pAccountids and runs for more than 8 hours.
SELECT /*+ INDEX(T TRXNS_ACCOUNTID_NIDX) */ AL.FROMACCOUNTID oldaccountid ,
A.ACCOUNTNUM oldaccountnum,
T.TRXNSID,
T.TRXNSTYPEID,
T.DESCRIPTION ,
T.postdt,
T.TRXNSAMT
FROM
ACCOUNTLINK AL,
TRXNS T,
ACCOUNT A
WHERE AL.TOACCOUNTID IN
(SELECT TOACCOUNTID FROM ACCOUNTLINK START WITH TOACCOUNTID = pAccountid
CONNECT BY PRIOR FROMACCOUNTID = TOACCOUNTID)
AND AL.FROMACCOUNTID = T.ACCOUNTID
AND A.ACCOUNTID = AL.FROMACCOUNTID
AND NOT EXISTS (select 1 from TRXNStrack trck where trck.TRXNSid = t.TRXNSid AND TRXNSTrackReasonid = 1)
AND T.postdt > A.CLOSEDATE
AND T.postdt >= sysdate-2
AND T.postdt <= sysdate;
Create script for trxn table:
CREATE TABLE SP.TRXNS
TRXNSID NUMBER(15) CONSTRAINT "BIN$rpIQEeyLDfbgRAAUT4DEnQ==$0" NOT NULL,
ACCOUNTID NUMBER(15) CONSTRAINT "BIN$rpIQEeyMDfbgRAAUT4DEnQ==$0" NOT NULL,
STATEMENTID NUMBER(15),
TRXNSTYPEID NUMBER(15),
DESCRIPTION VARCHAR2(80 BYTE),
postdt DATE,
TRXNSAMT NUMBER(12,2),
TRXNSREQID NUMBER(15),
LASTUPDATE DATE,
SOURCEID NUMBER(15),
HIDE VARCHAR2(1 BYTE)
TABLESPACE SO_TRXN_DATA
RESULT_CACHE (MODE DEFAULT)
PCTUSED 40
PCTFREE 10
INITRXNS 2
MAXTRXNS 255
STORAGE (
INITIAL 50M
NEXT 1M
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0
FREELISTS 8
FREELIST GROUPS 1
BUFFER_POOL DEFAULT
FLASH_CACHE DEFAULT
CELL_FLASH_CACHE DEFAULT
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;
CREATE INDEX SP.TRXNS_ACCOUNTID_NIDX ON SP.TRXNS
(ACCOUNTID, postdt)
LOGGING
TABLESPACE SO_TRXN_INDEX
PCTFREE 10
INITRXNS 2
MAXTRXNS 255
STORAGE (
INITIAL 64K
NEXT 1M
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0
FREELISTS 1
FREELIST GROUPS 1
BUFFER_POOL DEFAULT
FLASH_CACHE DEFAULT
CELL_FLASH_CACHE DEFAULT
NOPARALLEL;
below is the executing plan for this sql taken from toad :
PLAN_ID
TIMESTAMP
OPERATION
OPTIONS
OBJECT_OWNER
OBJECT_NAME
OBJECT_ALIAS
OBJECT_INSTANCE
OBJECT_TYPE
OPTIMIZER
SEARCH_COLUMNS
ID
PARENT_ID
DEPTH
POSITION
COST
CARDINALITY
BYTES
CPU_COST
IO_COST
TEMP_SPACE
ACCESS_PREDICATES
FILTER_PREDICATES
PROJECTION
TIME
QBLOCK_NAME
1121
9/10/2013 3:30
FILTER
1
0
1
1
NOT EXISTS (SELECT 0 FROM "TRXNSTRACK" "TRCK" WHERE "TRXNSTRACKREASONID"=1 AND "TRCK"."TRXNSID"=:B1)
AL."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
SEL$5DA710D3
1121
9/10/2013 3:30
FILTER
2
1
2
1
SYSDATE@!-2<=SYSDATE@!
AL."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
1121
9/10/2013 3:30
NESTED LOOPS
3
2
3
1
(#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
1121
9/10/2013 3:30
NESTED LOOPS
4
3
4
1
5
1
119
3989858
4
(#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A".ROWID[ROWID,10]
1
1121
9/10/2013 3:30
NESTED LOOPS
5
4
5
1
4
1
90
3989690
3
(#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22]
1
1121
9/10/2013 3:30
HASH JOIN
SEMI
6
5
6
1
3
2
54
3989094
2
AL."TOACCOUNTID"="TOACCOUNTID"
(#keys=1) "AL"."FROMACCOUNTID"[NUMBER,22]
1
1121
9/10/2013 3:30
INDEX
FULL SCAN
SP
ACCOUNTLINK_AK1
AL@SEL$1
INDEX (UNIQUE)
ANALYZED
7
6
7
1
1
18
252
107
1
AL."FROMACCOUNTID"[NUMBER,22], "AL"."TOACCOUNTID"[NUMBER,22]
1
SEL$5DA710D3
1121
9/10/2013 3:30
VIEW
SYS
VW_NSO_1
VW_NSO_1@SEL$5DA710D3
11
VIEW
8
6
7
2
2
18
234
107
1
TOACCOUNTID[NUMBER,22]
1
SEL$683B0107
1121
9/10/2013 3:30
CONNECT BY
NO FILTERING WITH START-WITH
9
8
8
1
TOACCOUNTID=PRIOR "FROMACCOUNTID"
TOACCOUNTID=56354162
TOACCOUNTID[NUMBER,22], "FROMACCOUNTID"[NUMBER,22], PRIOR NULL[22], LEVEL[4]
SEL$683B0107
1121
9/10/2013 3:30
INDEX
FULL SCAN
SP
ACCOUNTLINK_AK1
ACCOUNTLINK@SEL$3
INDEX (UNIQUE)
ANALYZED
10
9
9
1
1
18
252
107
1
ACCOUNTLINK.ROWID[ROWID,10], "FROMACCOUNTID"[NUMBER,22], "TOACCOUNTID"[NUMBER,22]
1
SEL$3
1121
9/10/2013 3:30
TABLE ACCESS
BY INDEX ROWID
SP
TRXNS
T@SEL$1
2
TABLE
ANALYZED
11
5
6
2
1
1
63
298
1
T."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22]
1
SEL$5DA710D3
1121
9/10/2013 3:30
INDEX
RANGE SCAN
SP
TRXNS_ACCOUNTID_NIDX
T@SEL$1
INDEX
ANALYZED
2
12
11
7
1
1
1
224
1
AL."FROMACCOUNTID"="T"."ACCOUNTID" AND "T"."POSTDT">=SYSDATE@!-2 AND "T"."POSTDT"<=SYSDATE@!
T.ROWID[ROWID,10], "T"."POSTDT"[DATE,7]
1
SEL$5DA710D3
1121
9/10/2013 3:30
INDEX
UNIQUE SCAN
SP
ACCOUNT_PK
A@SEL$1
INDEX (UNIQUE)
ANALYZED
1
13
4
5
2
1
1
90
1
A."ACCOUNTID"="AL"."FROMACCOUNTID"
A.ROWID[ROWID,10]
1
SEL$5DA710D3
1121
9/10/2013 3:30
TABLE ACCESS
BY INDEX ROWID
SP
ACCOUNT
A@SEL$1
3
TABLE
ANALYZED
14
3
4
2
1
1
29
168
1
A."CLOSEDATE"<SYSDATE@! AND "T"."POSTDT">"A"."CLOSEDATE"
A."ACCOUNTNUM"[VARCHAR2,19]
1
SEL$5DA710D3
1121
9/10/2013 3:30
INDEX
RANGE SCAN
SP
TRXNSTRACK_TRXNSID_NIDX
TRCK@SEL$6
INDEX
ANALYZED
2
15
1
2
2
1
1
10
73
1
TRCK."TRXNSID"=:B1 AND "TRXNSTRACKREASONID"=1
TRCK."TRXNSID"[NUMBER,22], "TRXNSTRACKREASONID"[NUMBER,22]
1
SEL$6
Please help me in debugging this thanks!Hi,
Thanks for your thought on this subject. Below is the trace info that I got from the DBA
SQL ID: d0x879qx2zgtz Plan Hash: 4036333519
SELECT /*+ INDEX(T TRXNS_ACCOUNTID_NIDX) */ AL.FROMACCOUNTID OLDACCOUNTID ,
A.ACCOUNTNUM OLDACCOUNTNUM, T.TRXNSID, T.TRXNSTYPEID, T.DESCRIPTION ,
T.POSTDT, T.TRXNSAMT
FROM
ACCOUNTLINK AL, TRXNS T, ACCOUNT A WHERE AL.TOACCOUNTID IN (SELECT
TOACCOUNTID FROM ACCOUNTLINK START WITH TOACCOUNTID = :B3 CONNECT BY PRIOR
FROMACCOUNTID = TOACCOUNTID) AND AL.FROMACCOUNTID = T.ACCOUNTID AND
A.ACCOUNTID = AL.FROMACCOUNTID AND NOT EXISTS (SELECT 1 FROM TRXNSTRACK
TRCK WHERE TRCK.TRXNSID = T.TRXNSID AND TRXNSTRACKREASONID = :B4 ) AND
T.POSTDT > A.CLOSEDATE AND T.POSTDT >= :B2 AND T.POSTDT <= :B1
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 17160 2.10 1.87 0 0 0 0
Fetch 17160 7354.61 7390.86 169408 5569856 883366791 0
total 34320 7356.71 7392.74 169408 5569856 883366791 0
Misses in library cache during parse: 0
Optimizer mode: CHOOSE
Parsing user id: 38 (recursive depth: 1)
SQL ID: gs89hpavb4cts Plan Hash: 3415795327
SELECT A.ACCOUNTID, C.MEMBERID, A.PROGRAMID, A.ACCOUNTNUM
FROM
CUSTOMER C, CUSTOMERACCOUNT CA, ACCOUNT A, PROGRAMPARAMVALUE PPV,
BATCHPROCESSPROGRAM BP WHERE A.PROGRAMID = BP.PROGRAMID AND A.PROGRAMID =
PPV.PROGRAMID AND A.ACCOUNTID = CA.ACCOUNTID AND CA.PERSONID = C.PERSONID
AND PPV.PARAMID = :B2 AND PPV.VALUE = 'Y' AND BP.PROCESSID = :B1 AND BP.RUN
= 'Y' AND A.ACCOUNTTYPEID = 4 AND A.ACCOUNTSTATUSID = 1 AND C.MEMBERID IS
NOT NULL
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 0 0.00 0.00 0 0 0 0
Fetch 172 13.14 115.34 80826 278650 0 17200
total 172 13.14 115.34 80826 278650 0 17200
Misses in library cache during parse: 0
Parsing user id: 38 (recursive depth: 1)
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 0 0.00 0.00 0 0 0 0
Fetch 0 0.00 0.00 0 0 0 0
total 0 0.00 0.00 0 0 0 0
Misses in library cache during parse: 0
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 17160 2.10 1.87 0 0 0 0
Fetch 17332 7367.75 7506.21 250234 5848506 883366791 17200
total 34492 7369.85 7508.09 250234 5848506 883366791 17200
Misses in library cache during parse: 0
2 user SQL statements in session.
0 internal SQL statements in session.
2 SQL statements in session.
Trace file: svoprod_ora_12346.trc
Trace file compatibility: 11.1.0.7
Sort options: default
1 session in tracefile.
2 user SQL statements in trace file.
0 internal SQL statements in trace file.
2 SQL statements in trace file.
2 unique SQL statements in trace file.
66499 lines in trace file.
7516 elapsed seconds in trace file. -
Connect by Prior in Oracle 8i question
Need help with building tree-structured query in Oracle 8i (Forms 6i front end if it matters).
Sample structure and data:
CREATE TABLE table_list
my_code NUMBER,
my_level NUMBER,
my_description VARCHAR2(60)
CREATE TABLE table_content
my_code NUMBER,
term_code NUMBER,
term_category VARCHAR2(5)
INSERT into table_list values (101, 1, 'building');
INSERT into table_list values (102, 2, 'flat');
INSERT into table_list values (103, 3, 'living room');
INSERT into table_list values (104, 3, 'bedroom');
INSERT into table_list values (105, 3, 'bathroom');
commit;
INSERT into table_content values (101, 102, 'Sub');
INSERT into table_content values (102, 103, 'Sub');
INSERT into table_content values (102, 104, 'Sub');
INSERT into table_content values (102, 105, 'Sub');
commit;
Need to display data in the following order:
101 'building' --level one
102 'flat' --level two
105 'bathroom' --level three
104 'bedroom' --level three
103 'living room' --level three
*(note alphabetical order in level three)*
Looks like Oracle 8i does not support table joins for CONNECT BY PRIOR. Please advise!And you are correct, it does not display level 1. Do
you think this is this a database structure problem
or it could be corrected via query modification?No and yes. It's not a "structure" problem, its a data problem (as I explained above). You always fix data problems by making queries overly complex (hint, hint, I don't suggest doing it this way).
select tl.my_level, tl.my_description , LPAD(' ',3*(my_level-1)) || substr(tl.my_description, 1, 30) description
from table_list tl,
(select term_Code from table_content
start with my_code in (select my_code from table_list where my_level=1)
connect by prior term_code = my_code
) x
where x.term_code = tl.my_code
union all
select my_level, my_description
from table_list
where my_level = 1
order by 1, 2
better to add a row to table_content with my_code=null, term_code=101.
otherwise you'll be pulling stupid nonsense like above with every query from here on out.
Maybe you are looking for
-
My laptop screen goes black when i plug in an Hdmi cord
Initially I had both my tv and computer off. I connected the dvi to the tv and the hdmi to the laptop and turned them both on. I had no issue using my laptop as i tried to sync the computer to the TV. However i must have accidentally hit something in
-
Streaming a movie from Flixster & using Bluetooth speakers, my wi-fi connection keeps dropping
When streaming a movie from Flixster and using Bluetooth speakers, my wi-fi connection keeps dropping, like every 2 seconds! Anyone have any suggestions on how to rectify this issue? In fact, I don't even have to be streaming the movie. When I was i
-
Deleted Files , By Netwok Sharing Driver
Hi! Everyone ,I use Windows server data center edition as a domain server ,i share a drive like ( D:\Share File ) for domain users , he work there and i permitted Delete and new create any file and folders( on the Shared Drive , But When he accidenta
-
Hi There, I,m Using Adobe Photoshop CS4 Extended And I,m Wondering If Theres Any Way To Remove The Big Empty Area Around My Canvas, It Gets Quite Annoying As I,m Used To CS2, If You Don't Understand What I Mean Here's A Screenshot. My canvas Stops Th
-
"No License to Play this track" messages
2"No License to Play this track" messages?There seems to be a lot of "no license to play this track" error messages here, but none seem to match mine. I use my ZEN MX for audible books. I transferred the files numerous ways from Netlibrary and they w