Oracle hierarchical query

hello all,
this is my data which is in my table.
CREATE TABLE  PRMATDTL
  COMPCODE  VARCHAR2(3 BYTE)                    NOT NULL,
  DOCNUMBR  VARCHAR2(8 BYTE)                    NOT NULL,
  CONTNUMB  VARCHAR2(8 BYTE)                    NOT NULL,
  DOCTDATE  DATE                                NOT NULL,
  CHGETYPE  VARCHAR2(3 BYTE)                    NOT NULL,
  PARENTNM  VARCHAR2(10 BYTE)                   NOT NULL,
  CHILDNAM  VARCHAR2(10 BYTE)                   NOT NULL,
  ITEMTYPE  VARCHAR2(3 BYTE),
  BOQUITEM  VARCHAR2(10 BYTE),
  LUOMCODE  VARCHAR2(10 BYTE),
  QUANTITY  VARCHAR2(1 BYTE),
  QTYPAMTR  NUMBER,
  WASTEPER  NUMBER,
  UNITRATE  NUMBER,
  CREATEDT  DATE                                NOT NULL,
  CREATEBY  VARCHAR2(6 BYTE)                    NOT NULL,
  OPRSTAMP  VARCHAR2(6 BYTE)                    NOT NULL,
  TIMSTAMP  DATE                                NOT NULL,
  APPORVBY  VARCHAR2(6 BYTE),
  APPROVDT  DATE,
  ACTVCODE  VARCHAR2(10 BYTE)
SET DEFINE OFF;
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    '0200000000', '0205001000', 'BOQ', '1', 'NOS',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:23:58', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:23:58', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    '0205001000', 'AC100377', 'ACT', NULL, 'NOS',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:24:05', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:05', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    '0205001000', 'AC104307', 'ACT', NULL, 'ROL',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:24:08', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:08', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC100377', '08000007', 'ITE', NULL, 'NOS',
    '3', NULL, 5, 20, TO_DATE('01/08/2014 09:24:22', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:22', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC100377', '08000007', 'ITR', NULL, 'NOS',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:24:22', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:22', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC104307', '04600034', 'ITE', NULL, 'ROL',
    '2', NULL, 2, 40, TO_DATE('01/08/2014 09:24:36', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:36', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC104307', '04600034', 'ITR', NULL, 'ROL',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:24:36', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:36', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    '0200000000', '0201009000', 'BOQ', '10', 'ITM',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:24:48', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:24:48', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    '0201009000', 'AC104903', 'ACT', NULL, 'NOS',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC104903', '00800090', 'ITE', NULL, 'COT',
    '1', NULL, 5, 60, TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'ADD',
    'AC104903', '00800090', 'ITR', NULL, 'COT',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:25:07', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
Insert into PRMATDTL
   (COMPCODE, DOCNUMBR, CONTNUMB, DOCTDATE, CHGETYPE,
    PARENTNM, CHILDNAM, ITEMTYPE, BOQUITEM, LUOMCODE,
    QUANTITY, QTYPAMTR, WASTEPER, UNITRATE, CREATEDT,
    CREATEBY, OPRSTAMP, TIMSTAMP, APPORVBY, APPROVDT,
    ACTVCODE)
Values
   ('100', 'CO130028', 'CM130124', TO_DATE('01/08/2014 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'DEL',
    '0100000000', '0101001000', 'BOQ', '1', 'ITM',
    NULL, NULL, NULL, NULL, TO_DATE('01/08/2014 09:35:10', 'MM/DD/YYYY HH24:MI:SS'),
    'SYSTEM', 'SYSTEM', TO_DATE('01/08/2014 09:35:10', 'MM/DD/YYYY HH24:MI:SS'), NULL, NULL,
    NULL);
COMMIT;
COMPCODE
DOCNUMBR
PARENTNM
CHILDNAM
ITEMTYPE
LUOMCODE
QUANTITY
QTYPAMTR
WASTEPER
UNITRATE
100
CO130028
200000000
205001000
BOQ
NOS
100
CO130028
205001000
AC100377
ACT
NOS
100
CO130028
205001000
AC104307
ACT
ROL
100
CO130028
AC100377
8000007
ITE
NOS
3
5
20
100
CO130028
AC100377
8000007
ITR
NOS
100
CO130028
AC104307
4600034
ITE
ROL
2
2
40
100
CO130028
AC104307
4600034
ITR
ROL
100
CO130028
200000000
201009000
BOQ
ITM
100
CO130028
201009000
AC104903
ACT
NOS
100
CO130028
AC104903
800090
ITE
COT
1
5
60
100
CO130028
AC104903
800090
ITR
COT
I want to show the data like this
COMPCODE
DOCNUMBR
LOCATION
BOQITEM
UNIT
ACTVCODE
UNIT_1
ITEMCODE
UNIT_2
QUANTITY
QTYPAMTR
WASTEPER
UNITRATE
100
CO130028
200000000
205001000
NOS
AC100377
NOS
8000007
NOS
100
CO130028
200000000
205001000
NOS
AC100377
NOS
8000007
NOS
3
5
20
100
CO130028
200000000
205001000
NOS
AC104307
ROL
4600034
ROL
100
CO130028
200000000
205001000
NOS
AC104307
ROL
4600034
ROL
2
2
40
100
CO130028
200000000
201009000
ITM
AC104903
NOS
800090
COT
100
CO130028
200000000
201009000
ITM
AC104903
NOS
800090
COT
1
5
60
I used one self inner join query
SELECT
  A1.COMPCODE,
  A1.DOCNUMBR,
  A1.ITEMTYPE,
  A1.LUOMCODE UNIT,
  A1.PARENTNM LOCATION,
  A1.CHILDNAM BOQITEM,
  A2.CHILDNAM ACTVCODE,
  A2.LUOMCODE UNIT,
  A3.CHILDNAM ITEMCODE,
  A3.LUOMCODE UNIT,
  A3.QUANTITY,
  A3.QTYPAMTR,
  A3.WASTEPER,
  A3. UNITRATE
FROM                   
  PRMATDTL A1,
  PRMATDTL A2,
  PRMATDTL A3
WHERE
  A1.CHILDNAM=A2.PARENTNM
  AND A2.CHILDNAM=A3.PARENTNM
  AND SUBSTR(A1.PARENTNM,3,10) = '00000000'
  AND A1.DOCNUMBR='CO130028'
  AND A2.DOCNUMBR='CO130028'
  AND A3.DOCNUMBR='CO130028';
But it seems very slow and very complicated ,I want another one query using with connect by prior ..
Please help me.

May be this
SQL> select * from test;
  COMPCODE DOCNUMBR PARENTNM  CHILDNAM  ITE LUO   QUANTITY   QTYPAMTR   WASTEPER   UNITRATE
       100 CO130028 200000000 205001000 BOQ NOS          0          0          0          0
       100 CO130028 205001000 AC100377  ACT NOS          0          0          0          0
       100 CO130028 205001000 AC104307  ACT ROL          0          0          0          0
       100 CO130028 AC100377  8000007   ITE NOS          3          5         20          0
       100 CO130028 AC100377  8000007   ITR NOS          0          0          0          0
       100 CO130028 AC104307  4600034   ITE ROL          2          2         40          0
       100 CO130028 AC104307  4600034   ITR ROL          0          0          0          0
       100 CO130028 200000000 201009000 BOQ ITM          0          0          0          0
       100 CO130028 201009000 AC104903  ACT NOS          0          0          0          0
       100 CO130028 AC104903  800090    ITE COT          1          5         60          0
       100 CO130028 AC104903  800090    ITR COT          0          0          0          0
11 rows selected.
SQL> select compcode
  2       , docnumbr
  3       , location
  4       , boqitem
  5       , unit
  6       , actvcode
  7       , unit_1
  8       , itemcode
  9       , unit_2
10       , quantity
11       , qtypamtr
12       , wasteper
13       , unitrate
14    from (
15            select compcode
16                 , docnumbr
17                 , parentnm actvcode
18                 , childnam itemcode
19                 , quantity
20                 , qtypamtr
21                 , wasteper
22                 , unitrate
23                 , connect_by_root(parentnm) location
24                 , connect_by_root(childnam) boqitem
25                 , last_value(decode(level, 1, luomcode) ignore nulls)
26                        over(order by rownum) unit
27                 , last_value(decode(level, 2, luomcode) ignore nulls)
28                        over(order by rownum) unit_1
29                 , last_value(decode(level, 3, luomcode) ignore nulls)
30                        over(order by rownum) unit_2
31                 , connect_by_isleaf is_leaf
32              from test
33             start with parentnm = '200000000'
34             connect by parentnm = prior childnam
35         )
36   where is_leaf = 1;
  COMPCODE DOCNUMBR LOCATION  BOQITEM   UNI ACTVCODE  UNI ITEMCODE  UNI   QUANTITY   QTYPAMTR   WASTEPER   UNITRATE
       100 CO130028 200000000 201009000 ITM AC104903  NOS 800090    COT          1          5         60          0
       100 CO130028 200000000 201009000 ITM AC104903  NOS 800090    COT          0          0          0          0
       100 CO130028 200000000 205001000 NOS AC100377  NOS 8000007   NOS          3          5         20          0
       100 CO130028 200000000 205001000 NOS AC100377  NOS 8000007   NOS          0          0          0          0
       100 CO130028 200000000 205001000 NOS AC104307  ROL 4600034   ROL          2          2         40          0
       100 CO130028 200000000 205001000 NOS AC104307  ROL 4600034   ROL          0          0          0          0
6 rows selected.

Similar Messages

  • [Oracle 8i] Need help pruning branches from a hierarchical query

    My problem is that my hierarchical query seems only to trim out the values that don't meet my criteria, but still includes their children. When my query hits a record that does not meet my criteria, I want it to stop there. I've tried including the criteria in just the 'where' clause of the query, and have also put the criteria in the 'connect by' clause as well, but nothing has fixed it. Please keep in mind I'm using Oracle 8i, so I can't use some of the 'nicer' statements for hierarchical queries that they introduced in 9. I'm stuck with 'Start With...Connect By'.
    I have sample tables/data that I can post if someone needs to see that to help me, but to start with, here's my current query:
    SELECT     *
    FROM     (
              SELECT
                   LEVEL
              ,     c_bill.comp_part_nbr                     AS     c_part_nbr
              ,     (select c_part.part_desc
                   FROM part c_part
                   WHERE c_part.part_nbr=c_bill.comp_part_nbr)     AS     c_part_desc
              ,     (SELECT c_part.part_type
                   FROM part c_part
                   WHERE c_part.part_nbr=c_bill.comp_part_nbr)      AS     c_part_type
              ,     c_bill.qty_per                          AS     c_qty_per_p
              ,     c_bill.qty_per_type                     AS     c_qty_per_type
              ,     (SELECT c_part.qty_on_hand                
                   FROM part c_part
                   WHERE c_part.part_nbr=c_bill.comp_part_nbr)      AS     c_qty_on_hand
              ,     c_bill.oper_nbr                     AS     rqd_at_op
              ,     c_bill.comp_off_adj                     AS     rqd_offset
              ,     c_bill.bom_doc_nbr                     AS     p_part_nbr
              ,     (SELECT p_part.qty_on_hand
                   FROM part p_part
                   WHERE p_part.part_nbr=c_bill.bom_doc_nbr)      AS     p_qty_on_hand
              FROM
                   BILL c_bill
              WHERE
                             (c_bill.status           =      'RL')           
                        AND     (c_bill.view_code     IN      ('M','G'))     
                        AND     (c_bill.end_eff_dt     >      SYSDATE)      
                        AND     (c_bill.begn_eff_dt     <=      SYSDATE)
              START WITH c_bill.bom_doc_nbr=RPAD(?,25)
              CONNECT BY PRIOR c_bill.comp_part_nbr=c_bill.bom_doc_nbr
              AND     c_bill.view_code     IN     ('M','G')     
              AND     c_bill.status          =     'RL'
              AND      c_bill.end_eff_dt     >     SYSDATE
              AND     c_bill.begn_eff_dt     <=     SYSDATE     
         ) a
    WHERE     c_part_type = 'M'

    The outside criterion of part_type='M' isn't my problem. Where I'm actually seeing my issue rear its ugly head is in the criterion:
    (c_bill.view_code     IN      ('M','G'))What I'll have happen is that one of the children or grandchildren of the part number I'm querying for (my parameter), will be of some view code that's not 'M' or 'G'. In my sample data below, I have a level 4 part that is part of the 'H' view code, which I don't want, nor do I want it's children. However, its child is in the 'G' view code, and my query returns it anyway.
    In my sample data below, I'm assuming that the parameter = 'XYZ-100'
    CREATE TABLE part
    part_nbr     varchar(25) not null,
    part_desc     varchar(25) not null,
    part_type     char(1) not null,
    qty_on_hand     double(13,4) not null
    CONSTRAINT part_pk
    PRIMARY KEY (part_nbr),
    CONSTRAINT check_part_type
    CHECK (part_type IN ('M','P','X','Y')),
    CONSTRAINT check_qty_on_hand
    CHECK (qty_on_hand >= 0)
    CREATE TABLE bill
    row_added_ts     char(20) not null,
    bom_doc_nbr     varchar(25) not null,
    comp_part_nbr     varchar(25) not null,
    qty_per          double(9,5) not null,
    qty_per_type     char(1) not null,
    oper_nbr     char(4) not null,
    comp_off_adj     double(3,0),
    status          char(2),
    view_code     char(1) not null,
    end_eff_dt     date() not null,
    begn_eff_dt     date() not null
    CONSTRAINT bill_pk
    PRIMARY KEY (row_added_ts),
    CONSTRAINT check_qty_per_type
    CHECK (qty_per_type IN ('0','1','2','3')),
    CONSTRAINT check_status
    CHECK (status IN ('IN', 'RL')),
    );     Values for those tables:
    INSERT INTO part
    VALUES ('xyz-1', 'purchased part', 'P', 5);
    INSERT INTO part
    VALUES ('xyz-2', 'purchased part', 'P', 1);
    INSERT INTO part
    VALUES ('xyz-3', 'purchased part', 'P', 1);
    INSERT INTO part
    VALUES ('xyz-3a', 'manufactured part', 'M', 1);
    INSERT INTO part
    VALUES ('xyz-4', 'purchased part', 'P', 1);
    INSERT INTO part
    VALUES ('xyz-9-1', 'manufactured part', 'M', 0);
    INSERT INTO part
    VALUES ('xyz-9a', 'manufactured part', 'M', 0);
    INSERT INTO part
    VALUES ('raw-1', 'purchased raw material', 'P', 212);
    INSERT INTO part
    VALUES ('raw-2', 'purchased raw material', 'P', 75.5);
    INSERT INTO part
    VALUES ('XYZ-100', 'manufactured part', 'M', 0);
    INSERT INTO part
    VALUES ('(OPEN)', '(not in use)', 'Y', 0);
    INSERT INTO part
    VALUES ('XYZ-100-1', 'manufactured part', 'M', 0);
    INSERT INTO part
    VALUES ('XYZ-100-2', 'manufactured part', 'M', 1);
    INSERT INTO part
    VALUES ('XYZ-100-3', 'manufactured part', 'M', 0);
    INSERT INTO part
    VALUES ('XYZ-100-4', 'manufactured part', 'M', 2);
    INSERT INTO part
    VALUES ('XYZ-100-A', 'manufactured part', 'M', 0);
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100','xyz-1',3,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100','XYZ-100-1',1,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-1','xyz-1',2,'1','****',1,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-1','XYZ-100-2',3,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-2','xyz-2',6,'1','****',2,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-2','xyz-4',6,'1','****',2,'IN','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-2','xyz-100-3',1,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-3','xyz-3',8,'1','****',1,'RL','M','01-Jan-2050','01-Jan-2000');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-3','xyz-3a',8,'1','****',1,'RL','M','01-Jan-2000','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-3','XYZ-100-4',4,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-3','XYZ-100-A',2,'1','****',2,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008071153100150000','XYZ-100-3','(OPEN)',2,'1','****',0,'RL','E','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008071153100150000','XYZ-100-3','xyz-9-1',2,'1','****',0,'RL','H','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-4','raw-1',8.75,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008072153100150000','XYZ-100-A','raw-2',3.75,'1','****',0,'RL','M','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008075911100150000','xyz-9-1','xyz-9a',1,'1','****',0,'RL','G','01-Jan-2050','01-Jan-1900');
    INSERT INTO bill
    VALUES ('2008087711100150000','xyz-9a','raw-2',3.75,'1','****',0,'RL','G','01-Jan-2050','01-Jan-1900');Sample data displayed in table format:
    --PART table (from insert statements above)
    part_nbr     part_desc          part_type     qty_on_hand
    xyz-1           purchased part          P          5
    xyz-2           purchased part          P          1
    xyz-3           purchased part          P          1
    xyz-3a           manufactured part     M          1
    xyz-4           purchased part          P          1
    xyz-9-1           manufactured part     M          0
    xyz-9a           manufactured part     M          0
    raw-1           purchased raw material     P          212
    raw-2           purchased raw material     P          75.5
    XYZ-100           manufactured part     M          0
    (OPEN)          (not in use)          Y          0
    XYZ-100-1     manufactured part     M          0
    XYZ-100-2     manufactured part     M          1
    XYZ-100-3     manufactured part     M          0
    XYZ-100-4     manufactured part     M          2
    XYZ-100-A     manufactured part     M          0
    --BILL table (from insert statements above)
    row_added_ts          bom_doc_nbr     comp_part_nbr     qty_per     qty_per_type     oper_nbr     comp_off_adj     status     view_code     end_eff_dt     begn_eff_dt
    2008072153100150000     XYZ-100          xyz-1          3     1          ****          0          RL     G          01-Jan-2050     01-Jan-1900
    2008072223100150000     XYZ-100          XYZ-100-1     1     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008072411100150000     XYZ-100-1     xyz-1          2     1          ****          1          RL     M          01-Jan-2050     01-Jan-1900
    2008072459100150000     XYZ-100-1     XYZ-100-2     3     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008072578100150000     XYZ-100-2     xyz-2          6     1          ****          2          RL     M          01-Jan-2050     01-Jan-1900
    2008072694100150000     XYZ-100-2     xyz-4          6     1          ****          2          IN     G          01-Jan-2050     01-Jan-1900
    2008072786100150000     XYZ-100-2     xyz-100-3     1     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008072865100150000     XYZ-100-3     xyz-3          8     1          ****          1          RL     M          01-Jan-2050     01-Jan-2000
    2008073100100150000     XYZ-100-3     xyz-3a          8     1          ****          1          RL     M          01-Jan-2000     01-Jan-1900
    2008073159100150000     XYZ-100-3     XYZ-100-4     4     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008073346100150000     XYZ-100-3     XYZ-100-A     2     1          ****          2          RL     M          01-Jan-2050     01-Jan-1900
    2008073478100150000     XYZ-100-3     (OPEN)          2     1          ****          0          RL     E          01-Jan-2050     01-Jan-1900
    2008073529100150000     XYZ-100-3     xyz-9-1          2     1          ****          0          RL     H          01-Jan-2050     01-Jan-1900
    2008073798100150000     XYZ-100-4     raw-1          8.75     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008073811100150000     XYZ-100-A     raw-2          3.75     1          ****          0          RL     M          01-Jan-2050     01-Jan-1900
    2008075911100150000     xyz-9-1          xyz-9a          1     1          ****          0          RL     G          01-Jan-2050     01-Jan-1900
    2008087711100150000     xyz-9a          raw-2          3.75     1          ****          0          RL     G          01-Jan-2050     01-Jan-1900--What I want to get with my query (branches pruned off my tree)
    LEVEL     C_PART_NBR     C_PART_DESC          C_PART_TYPE     C_QTY_PER_P     C_QTY_PER_TYPE     C_QTY_ON_HAND     RQD_AT_OP     RQD_OFFSET     P_PART_NBR     P_QTY_ON_HAND
    1     XYZ-100-1     manufactured part     M          1          1          0          ****          0          XYZ-100          0
    2     XYZ-100-2     manufactured part     M          3          1          1          ****          0          XYZ-100-1     0
    3     xyz-100-3     manufactured part     M          1          1          0          ****          0          XYZ-100-2     1
    4     XYZ-100-4     manufactured part     M          4          1          2          ****          0          XYZ-100-3     0
    4     XYZ-100-A     manufactured part     M          2          1          0          ****          2          XYZ-100-3     0--What I actually get with my query (includes children of items that don't meet query criteria)
    LEVEL     C_PART_NBR     C_PART_DESC          C_PART_TYPE     C_QTY_PER_P     C_QTY_PER_TYPE     C_QTY_ON_HAND     RQD_AT_OP     RQD_OFFSET     P_PART_NBR     P_QTY_ON_HAND
    1     XYZ-100-1     manufactured part     M          1          1          0          ****          0          XYZ-100          0
    2     XYZ-100-2     manufactured part     M          3          1          1          ****          0          XYZ-100-1     0
    3     xyz-100-3     manufactured part     M          1          1          0          ****          0          XYZ-100-2     1
    4     XYZ-100-4     manufactured part     M          4          1          2          ****          0          XYZ-100-3     0
    4     XYZ-100-A     manufactured part     M          2          1          0          ****          2          XYZ-100-3     0
    5     xyz-9a          manufactured part     M          1          1          0          ****          0          xyz-9-1          0Edited by: user11033437 on Jul 30, 2009 7:27 AM (grammar)

  • How to convert SQL Server hierarchical query (CTE) to Oracle?

    How to convert SQL Server hierarchical query (CTE) to Oracle?
    WITH cte (col1, col2) AS
    SELECT col1, col2
    FROM dbo.[tb1]
    WHERE col1 = 12
    UNION ALL
    SELECT c.col1, c.col2
    FROM dbo.[tb1] AS c INNER JOIN cte AS p ON c.col2 = p.col1
    DELETE a
    FROM dbo.[tb1] AS a INNER JOIN cte AS b
    ON a.col1 = b.col1

    See: http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#i2129904
    Ah, just spotted it's a delete statement - you won't be able to do it using subquery factoring in Oracle.
    I had a go at trying to convert for you, but notice that you reference the cte from inside the cte... I can only assume you have a table called cte too...
    DELETE FROM dbo.tb1
    WHERE col1 = 12
    OR col2 IN (SELECT col1 FROM cte)
    Edited by: Boneist on 22-Jun-2009 09:19

  • ORACLE 9I의 HIERARCHICAL QUERY의 ORDER SIBLINGS BY CLAUSE

    제품 : ORACLE SERVER
    작성날짜 : 2003-10-22
    (V9I) Oracle 9i의 Hierarchical query의 ORDER SIBLINGS BY CLAUSE
    ===============================================================
    PURPOSE
    이 문서는 Oracle 9i의 new feature인 ORDER SIBLINGS BY 절을
    Hierarchical query에 사용하는 예를 통하여 특정 컬럼을 기준으로
    Ordering된 형태로 display하는 방법을 보여준다.
    Explanation & Example
    Hierarchical query를 구현할 때 ORDER BY 절을 사용하는 것은
    Oracle 7.1 버젼부터 가능한 것이었다.
    그러나, 순서대로 ordering되지 않고 특정 컬럼(emp table의 ename)을
    기준으로 ordering하기를 원한다면 <Bulletin:10373>처럼 procedure를
    작성하여야만 하였다.
    그러나, Oracle 9i 에서는 ORDER BY 절 대신에 ORDER SIBLINGS BY 절을
    사용할 수 있어 user-defined stored procedure를 만들 필요가 없게 되었다.
    1) Ordering 하기 전의 emp table의 Hierarchical query
    SQL> @a
    ename EMPNO MGR JOB
    KING 7839 PRESIDENT
    JONES 7566 7839 MANAGER
    SCOTT 7788 7566 ANALYST
    ADAMS 7876 7788 CLERK
    FORD 7902 7566 ANALYST
    SMITH 7369 7902 CLERK
    BLAKE 7698 7839 MANAGER
    ALLEN 7499 7698 SALESMAN
    WARD 7521 7698 SALESMAN
    MARTIN 7654 7698 SALESMAN
    TURNER 7844 7698 SALESMAN
    ename EMPNO MGR JOB
    JAMES 7900 7698 CLERK
    CLARK 7782 7839 MANAGER
    MILLER 7934 7782 CLERK
    14 rows selected.
    Ordering 하기 전의 a.sql 은 다음과 같다.
    col ename format a25
    col empno format 99999
    col mgr format 99999
    col job format a15
    select rpad(' ', LEVEL*5) || ename "ename", empno, mgr, job
    from emp
    start with job='PRESIDENT'
    connect by prior empno=mgr;
    2) 9i의 new feature인 Hierarchical query를 사용하여 Ordering한 경우
    SQL> @new_a
    ename EMPNO MGR JOB
    KING 7839 PRESIDENT
    BLAKE 7698 7839 MANAGER
    ALLEN 7499 7698 SALESMAN
    JAMES 7900 7698 CLERK
    MARTIN 7654 7698 SALESMAN
    TURNER 7844 7698 SALESMAN
    WARD 7521 7698 SALESMAN
    CLARK 7782 7839 MANAGER
    MILLER 7934 7782 CLERK
    JONES 7566 7839 MANAGER
    FORD 7902 7566 ANALYST
    ename EMPNO MGR JOB
    SMITH 7369 7902 CLERK
    SCOTT 7788 7566 ANALYST
    ADAMS 7876 7788 CLERK
    14 rows selected.
    Ordering하기 위해 사용한 new_a.sql 은 다음과 같다.
    col ename format a25
    col empno format 99999
    col mgr format 99999
    col job format a15
    select rpad(' ', LEVEL*5) || ename "ename", empno, mgr, job
    from emp
    start with job='PRESIDENT'
    connect by prior empno=mgr
    order siblings by ename;
    Reference Documents
    <Bulletin:10373>

    Thanks to Kendenny, Boneist and Odie.
    Got the point that "Order Siblings by clause" cannot be used with connect by query with analytical function, Thanks Kendenny.
    Yes, I now use main query and subquery, however the subquery be just "connect by" and have the all html tags added in the main query.
    The below query is working now.
    SELECT
    CASE WHEN LAG(mylevel,1,0) OVER (ORDER BY myrownum) >= mylevel THEN '<li>'
    ELSE
    CASE LEAD(mylevel) OVER (ORDER BY myrownum)
    WHEN mylevel THEN
    CASE WHEN myrownum = 1 THEN '<ul id="sidebarmenu1" '
    ELSE '<ul'
    END ||'><li>'
    ELSE
    CASE WHEN myrownum =1 THEN '<ul id="sidebarmenu1"'
    ELSE '<ul '
    END ||' ><li>'
    END
    END ||'<a href="'||
       CASE WHEN link_url IS NOT NULL THEN
          link_url||'title="'||menu_item||'"'
    ELSE '#"' END ||
    '><span>'||short_menu_item||'</span></a>'||
    CASE mylevel - LEAD(mylevel,1,1) OVER (ORDER BY myrownum)
    WHEN -1 THEN NULL
    WHEN 0 THEN '</li>'
    ELSE REPLACE(LPAD('*', myleveL-LEAD(mylevel,1,1) OVER (ORDER BY myrownum),'*'), '*','</li></ul></li>')
    END ||
    CASE WHEN LEAD(mylevel,1,0) OVER (ORDER BY myrownum) = 0 THEN '</ul>'
    ELSE NULL END unordered_List,
    menu_item, menu_id,
    above_menu_id
    FROM (
    SELECT LEVEL mylevel, ROWNUM myrownum,daevmt.*
    FROM dae_vs_my_tasks daevmt
    CONNECT BY PRIOR daevmt.menu_id = daevmt.above_menu_id
    START WITH daevmt.above_menu_id = 'TOPMENU'
    ORDER SIBLINGS BY display_order
    ) t;
    Odie, I tried altering the session for the flag, still the first query was not working.
    Thanks again all for your great time in answering me.

  • Slow Hierarchical Query

    Hi,
    I have a hierarchical query which takes 2 seconds to execute. I need to get this down to milli seconds.
    The table has around 8000 records. The query will never return more than 20 or so records. There is only ever 2 levels to the query.
    I am quite surprised at this because it is a very simple query no table joins etc and I would have though 8000 records was nothing for Oracle.
    Select id, parent_id, col1, col2, col3, col4, col5, col6
    from my_table
    where id=500
    start with parent_id is null
    connect by prior id = parent_id;
    I have even tried initializing the start with say with 0 and making it a not null column...... indexing the columns used in the start with + connect by
    I have tried various indexing stratergies. Does anyone have any similar experience? I am using Oracle 9i.
    Thanks in advance

    How can I utilise the above query in a view if at all? Will I be able to pass in differnt ID's to the START WITH...?Certainly, you can. For example, you can use packaged
    public variable to pass a parameter or Oracle CONTEXT:
    SQL> create or replace package pass_param is
      2    empno emp.empno%TYPE;
      3    function get_empno return emp.empno%TYPE;
      4  end;
      5  /
    &nbsp
    Package created.
    &nbsp
    SQL> create or replace package body pass_param is
      2    function get_empno return emp.empno%TYPE
      3    is
      4    begin
      5      return empno;
      6    end; 
      7  end;
      8  /
    &nbsp
    Package body created.
    &nbsp
    SQL> create or replace view emp_v as
      2  select ename from emp
      3  start with empno = pass_param.get_empno
      4  connect by prior empno = mgr
      5  /
    &nbsp
    View created.
    &nbsp
    SQL> exec pass_param.empno := 7839;
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select * from emp_v;
    &nbsp
    ENAME
    KING
    JONES
    SCOTT
    ADAMS
    FORD
    SMITH
    BLAKE
    ALLEN
    WARD
    MARTIN
    TURNER
    JAMES
    CLARK
    MILLER
    &nbsp
    14 rows selected.
    &nbsp
    SQL>  exec pass_param.empno := 7698;
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select * from emp_v;
    &nbsp
    ENAME
    BLAKE
    ALLEN
    WARD
    MARTIN
    TURNER
    JAMES
    &nbsp
    6 rows selected. or:
    SQL> create or replace package set_param
      2  is
      3   procedure set_empno(empno in number);
      4  end;
      5  /
    &nbsp
    Package created.
    &nbsp
    SQL> create or replace package body set_param
      2  is
      3   procedure set_empno(empno in number)
      4   is
      5   begin
      6     dbms_session.set_context('empnamespace','empno',empno);
      7   end;
      8  end;
      9  /
    &nbsp
    Package body created.
    &nbsp
    SQL> create or replace context empnamespace using set_param;
    &nbsp
    Context created.
    &nbsp
    SQL> create or replace view emp_v as
      2  select ename from emp
      3  start with empno = sys_context('empnamespace','empno')
      4  connect by prior empno = mgr
      5  /
    &nbsp
    View created.
    &nbsp
    SQL> exec set_param.set_empno(7698);
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select * from emp_v;
    &nbsp
    ENAME
    BLAKE
    ALLEN
    WARD
    MARTIN
    TURNER
    JAMES
    &nbsp
    6 rows selected.
    &nbsp
    SQL> exec set_param.set_empno(7839);
    &nbsp
    PL/SQL procedure successfully completed.
    &nbsp
    SQL> select * from emp_v;
    &nbsp
    ENAME
    KING
    JONES
    SCOTT
    ADAMS
    FORD
    SMITH
    BLAKE
    ALLEN
    WARD
    MARTIN
    TURNER
    JAMES
    CLARK
    MILLER
    &nbsp
    14 rows selected.Rgds.

  • A help with a hierarchical query

    I've got two tables:
    FOLDERS where relevant fields are: folderId, parentFolderId, folderQuota
    and DOCUMENTS where the relevant fields are: folderId, size
    FOLDERS is hierarchical - parentFolderId of a child's folder is set to folderId of the parent
    folderQuota is nullable (quota not set)
    Now, I need to execute a query with the following recursive logic
    <i>function calcQuota (folderIdpar, isFirstpar) {
    if (not isFirstpar) and (folderQuota of folder with folderIdpar is not null) return folderQuota;
    return size of all documents where folderId = folderIdpar + calcQuota (folderId of all children, false);
    }</i>
    (I hope the pseudocode is understandable - the query is executed as <i>calcQuota(originalFolderId, true)</i>).
    Now, my question is if I can achieve it with a single hierarchical query, or if I have to implement it as a recursive stored procedure.
    Thanks!
    P.S. I'm using Oracle XE (10g)

    OK,
    I will need to create it (in real life it is created by an application), so I hope I will make it correct. If not, it should be easy to fix.
    create table folders (
    folder_id number primary key
    parent_folder_id number,
    quota number
    create table documents (
    document_id number primary key
    folder_id number,
    size number
    INSERT INTO folders (folder_id, quota) VALUES (1, 1);
    INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (2, 1, 2);
    INSERT INTO folders (folder_id, parent_folder_id) VALUES (3, 1);
    INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (4, 2, 4);
    INSERT INTO folders (folder_id, parent_folder_id) VALUES (5, 2);
    INSERT INTO folders (folder_id, parent_folder_id, quota) VALUES (6, 3, 8);
    INSERT INTO folders (folder_id, parent_folder_id) VALUES (7, 3);
    INSERT INTO documents (document_id, folder_id, size) VALUES (1, 1, 16);
    INSERT INTO documents (document_id, folder_id, size) VALUES (2, 2, 32);
    INSERT INTO documents (document_id, folder_id, size) VALUES (3, 3, 64);
    INSERT INTO documents (document_id, folder_id, size) VALUES (4, 3, 128);
    INSERT INTO documents (document_id, folder_id, size) VALUES (5, 4, 256);
    INSERT INTO documents (document_id, folder_id, size) VALUES (6, 5, 512);
    INSERT INTO documents (document_id, folder_id, size) VALUES (7, 6, 1024);
    INSERT INTO documents (document_id, folder_id, size) VALUES (8, 7, 2048);
    running the query for folder_id = 1 should return 1 + 2 + 64 + 128 + 8 + 2048 = 2251
    running the query for folder_id = 2 should return 4 + 512 = 516
    I have decided for this data, because it allows to track what values (folder.quota or document.size) is included in the result.
    (it is the knapsack problem - see http://en.wikipedia.org/wiki/Knapsack_problem)
    P.S. I'm leaving for three weeks, so I will come back after that.

  • Problem with different execution paths in hierarchical query

    Hello,
    I have problems with the following query:
    SELECT DISTINCT P.ID FROM PRODUCTELEMENTIMPL P WHERE ( ( LABEL = 'SomeLabel' AND PRODUCTELEMENTTYPE = 'SomeText' AND ( STATE = 'created' OR STATE = 'stored' OR STATE = 'archived' OR STATE = 'archivedRestored' ) ) ) START WITH P.ID = 42 CONNECT BY PRIOR P.ID = P.PARENT
    We have two databases (an Oracle 10g XE and Oracle10g Enterprise). In the XE Database the query is executed very fast, but in the main installation it takes minutes. If I "explain" the query I get two different execution paths:
    The fast:
    ID      PARENT_ID      LEVEL      SQL      Kosten      Anzahl Zeilen
    0      -      1      SELECT STATEMENT      20      49
    1      0      2      HASH UNIQUE      20      49
    2      1      3      FILTER      -      -
    3      2      4      CONNECT BY WITH FILTERING      -      -
    4      3      5      TABLE ACCESS BY INDEX ROWID PRODUCTELEMENTIMPL (TABLE)      -      -
    5      4      6      INDEX UNIQUE SCAN SYS_C0072201 (INDEX (UNIQUE))      2      1
    6      3      5      NESTED LOOPS      -      -
    7      6      6      BUFFER SORT      -      -
    8      7      7      CONNECT BY PUMP      -      -
    9      6      6      TABLE ACCESS BY INDEX ROWID PRODUCTELEMENTIMPL (TABLE)      19      49
    10      9      7      INDEX RANGE SCAN PRODUCTELEMENTIMPL_IDX1 (INDEX)      3      49
    11      3      5      TABLE ACCESS FULL PRODUCTELEMENTIMPL (TABLE)      19      49
    Slow:
    ID PARENT_ID LEVEL SQL Kosten Anzahl Zeilen
    0 1 SELECT STATEMENT 1 1
    1 0 2 HASH UNIQUE 1 1
    2 1 3 FILTER
    3 2 4 CONNECT BY WITHOUT FILTERING
    4 3 5 TABLE ACCESS BY INDEX ROW 3 1
    ID PRODUCTELEMENTIMPL (TABLE)
    5 4 6 INDEX UNIQUE SCAN SYS_C0 2 1
    020528 (INDEX (UNIQUE))
    6 3 5 TABLE ACCESS FULL PRODUCT 6628 1100613
    ELEMENTIMPL (TABLE)
    Any ideas how to avoid this full table scan?
    bye
    Roland Spatzenegger

    Hello,
    thank you for your replies. The indices and table schemas are the "same", but only the content for the tables was mirrored.
    We made some tests with dropping and/or analyzing the tables, but it didn't change anything.
    The main problem is that the query takes 33s in the productive environment for searching in a couple of rows. At the moment it's faster to make
    SELECT DISTINCT P.ID, P.STATE FROM PRODUCTELEMENTIMPL P WHERE ( ( LABEL = 'SomeLabel' AND PRODUCTELEMENTTYPE = 'SomeText' ) ) START WITH P.ID = 42 CONNECT BY PRIOR P.ID = P.PARENT
    and to test in the application if the state-values match ;-)
    If I add the hint /*+ no_filtering */ in the test environment, I get the same "slow" execution path as in the production environment. So the question is, what prevents the filtering in "connect by"?
    (I think in the fast version it filters only the results of the hierarchical query, in the slow version it first filters the whole table and joins/merge it with the hierachical result).
    bye
    Roland Spatzenegger

  • Hierarchical Query Duplication Issue

    Hi All,
    I am trying to create a tree structure for a "NOT SO" elegantly structured data(for tree type traversing). The below mentioned query is the sample of the data that I have in the real-time system.
    The assumption & requirements to be considered are as follows:
    1. The query with the rep data(i.e. first WITH clause query with 9 rows) is the master data that needs to be shown in hierarchical structure.
    2. The query with the group data is joined with the rep data on GROUP_ID to get the tree structure be traversing on group_id and PARENT_GROUP_ID(i.e. Second WITH clause query)
    The problem is I am getting 16 rows instead of 9(which are expected since the master rep data query has 9 rows). Some part of the Tress is getting wrongly duplicated.
    Can anybody please point to me where I am making any mistake in the way this hierarchical query is written.
    SELECT
      REP_EMAIL
    ,REP_TYPE
    ,GROUP_MGR_EMAIL
    ,GROUP_ID
    ,PARENT_GROUP_ID
    ,RPAD('*',LEVEL*10,'*')||REP_EMAIL REP_EMAIL
    -- ,RPAD('*',LEVEL*10,'*')||GROUP_MGR_EMAIL GROUP_MGR_EMAIL
    ,SYS_CONNECT_BY_PATH(REP_EMAIL, '/') "Path"
      FROM (
          SELECT * FROM (
                       WITH REP AS(
                                     SELECT '[email protected]' AS EMAIL, 'REP' AS REP_TYPE, 112 AS GROUP_ID, 112 AS PARENT_GROUP_ID FROM DUAL UNION
                                     SELECT '[email protected]', 'REP' , 112 , 112 FROM DUAL UNION
                                     SELECT '[email protected]', 'REP' , 115 , 115 FROM DUAL UNION
                                     SELECT '[email protected]', 'REP' , 115 , 115 FROM DUAL UNION
                                     SELECT '[email protected]', 'MGR' , 112 , 117  FROM DUAL UNION
                                     SELECT '[email protected]', 'MGR' , 115 , 119 FROM DUAL UNION
                                     SELECT '[email protected]', 'MGR' , 117 , 2 FROM DUAL UNION
                                     SELECT '[email protected]', 'MGR' , 119 , 2 FROM DUAL UNION
                                     SELECT '[email protected]', 'REP' , 115 , 115  FROM DUAL
                                     SELECT EMAIL AS REP_EMAIL, REP_TYPE, GROUP_ID AS REP_GROUP_ID, PARENT_GROUP_ID AS REP_PARENT_GROUP_ID
                                       FROM REP) REP
       JOIN (
             SELECT * FROM (
                         WITH GRP AS (
                                     SELECT 1 AS GROUP_ID, NULL AS PARENT_GROUP_ID, '[email protected]' AS GROUP_MGR_EMAIL FROM DUAL UNION
                                     SELECT 2 , 1 , '[email protected]' FROM DUAL UNION
                                     SELECT 50 , 2 , '[email protected]' FROM DUAL UNION
                                     SELECT 112 , 117 , '[email protected]' FROM DUAL UNION
                                     SELECT 115 , 119 , '[email protected]' FROM DUAL UNION
                                     SELECT 117 , 2 , '[email protected]' FROM DUAL UNION
                                     SELECT 119 , 2 , '[email protected]' FROM DUAL
                                    SELECT GROUP_ID,  PARENT_GROUP_ID, GROUP_MGR_EMAIL
                                      FROM GRP) GRP) GRP
       ON (REP.REP_PARENT_GROUP_ID = GRP.GROUP_ID))
        START WITH PARENT_GROUP_ID = 1
      CONNECT BY   PARENT_GROUP_ID = PRIOR GROUP_IDAny help would be really appreciated.
    Thank you,
    Warm Regards
    Goldi

    Goldi wrote:
    The problem is I am getting 16 rows instead of 9(which are expected since the master rep data query has 9 rows). Some part of the Tress is getting wrongly duplicated. I don't think it is getting wrongly duplicated...
    SQL> ed
    Wrote file afiedt.buf
      1  WITH REP AS (SELECT EMAIL AS REP_EMAIL, REP_TYPE, GROUP_ID AS REP_GROUP_ID, PARENT_GROUP_ID AS REP_PARENT_GROUP_ID
      2               FROM (
      3                     SELECT '[email protected]' AS EMAIL, 'REP' AS REP_TYPE, 112 AS GROUP_ID, 112 AS PARENT_GROUP_ID FROM DUAL UNION
      4                     SELECT '[email protected]'        , 'REP'            , 112            , 112            FROM DUAL UNION
      5                     SELECT '[email protected]'        , 'REP'            , 115            , 115            FROM DUAL UNION
      6                     SELECT '[email protected]'        , 'REP'            , 115            , 115            FROM DUAL UNION
      7                     SELECT '[email protected]'         , 'MGR'            , 112            , 117            FROM DUAL UNION
      8                     SELECT '[email protected]'        , 'MGR'            , 115            , 119            FROM DUAL UNION
      9                     SELECT '[email protected]'        , 'MGR'            , 117            , 2              FROM DUAL UNION
    10                     SELECT '[email protected]'        , 'MGR'            , 119            , 2              FROM DUAL UNION
    11                     SELECT '[email protected]'         , 'REP'            , 115            , 115            FROM DUAL
    12                    )
    13              )
    14      ,GRP AS (
    15               SELECT 1 AS GROUP_ID, NULL AS PARENT_GROUP_ID, '[email protected]' AS GROUP_MGR_EMAIL FROM DUAL UNION
    16               SELECT 2            , 1                      , '[email protected]'                   FROM DUAL UNION
    17               SELECT 50           , 2                      , '[email protected]'                   FROM DUAL UNION
    18               SELECT 112          , 117                    , '[email protected]'                     FROM DUAL UNION
    19               SELECT 115          , 119                    , '[email protected]'                    FROM DUAL UNION
    20               SELECT 117          , 2                      , '[email protected]'                    FROM DUAL UNION
    21               SELECT 119          , 2                      , '[email protected]'                    FROM DUAL
    22              )
    23  --
    24  SELECT REP_EMAIL
    25        ,REP_TYPE
    26        ,GROUP_MGR_EMAIL
    27        ,GROUP_ID
    28        ,PARENT_GROUP_ID
    29       -- ,RPAD('*',LEVEL*10,'*')||REP_EMAIL REP_EMAIL
    30       -- ,RPAD('*',LEVEL*10,'*')||GROUP_MGR_EMAIL GROUP_MGR_EMAIL
    31       -- ,SYS_CONNECT_BY_PATH(REP_EMAIL, '/') "Path"
    32  FROM   REP JOIN GRP ON (REP.REP_PARENT_GROUP_ID = GRP.GROUP_ID)
    33  --CONNECT BY PARENT_GROUP_ID = PRIOR GROUP_ID
    34* --START WITH PARENT_GROUP_ID = 1
    SQL> /
    REP_EMAIL                                                    REP GROUP_MGR_EMAIL     GROUP_ID PARENT_GROUP_ID
    [email protected]                                             REP [email protected]          112          117
    [email protected]                                             REP [email protected]         115          119
    [email protected]                                             REP [email protected]         115          119
    [email protected]                                              REP [email protected]          112          117
    [email protected]                                              REP [email protected]         115          119
    [email protected]                                             MGR [email protected]         119            2
    [email protected]                                             MGR [email protected]          2            1
    [email protected]                                             MGR [email protected]          2            1
    [email protected]                                              MGR [email protected]         117            2
    9 rows selected.There are multiple matches in REP for the parent group id's. e.g. xyz2@.. and xyz3@.. both have a parent of 2 so you'll get duplicated branches from that as the connect by is going on the group id's e.g.
    1
      2
         117
             112
             112
         119
             115
             115
             115
      2
         117
             112
             112
         119
             115
             115
             115The duplicates are caused by the rows in REP. So Oracle is doing what you are asking of it because there is nothing further to restrict the connection to make one branch of 2 unique from the other branch of 2

  • Joins in Hierarchical Query

    I'm trying to use a Hierarchical Query with table joins in the "FROM" clause. According to the documentation, this will work with Oracle 9i and above.
    My problem is that in some queries, using the "JOIN" syntax works correctly but in others, it gives an "ORA-00928" message.
    If I change the query that gives the error to use old style Oracle joins (using the where clause), the query works.
    Can anyone help me to identify the problem?

    Here's the query. Again, note that if I use the old oracle join syntax (using where clause) it works:
    select level
    , biu.parent_part_no
    , biu.parent_part_serial_no
    , biu.comp_part_qty
    , cpi.part_no
    , cpi.serial_number
    , cpi.trace_code
    from bom.bom_instance_usage biu
    join bom.bom_part_instance cpi
    on cpi.bom_part_instance_key = iu.comp_part_instance_key
    start with ( biu.parent_part_no = '123456'
    and biu.parent_part_serial_no = '114' )
    connect by ( biu.parent_part_no = prior cpi.part_no
    and biu.parent_part_serial_no = prior cpi.serial_number )

  • Reg : Hierarchical Query(Using Connect By)

    Hi all,
    I got the result with the hierarchical query as :
    */qxxh*
    */qxxh/jxobcbg*
    */qxxh/jxobcbg/n00wcp4*
    */qxxh/jxobcbg/n00wcp4/x000263*
    */qxxh/jxobcbg/n00wcp4/x000263/p0263*
    */qxxh/jxxocbg*
    */qxxh/jxxocbg/n00voc1*
    */qxxh/jxxocbg/n00voc1/x000589*
    */qxxh/jxxocbg/n00voc1/x000589/p0589*
    */qxxh/jxuwxxh*
    */qxxh/jxuwxxh/n00xpxf*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl/x000522*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl/x000522/p0522*
    Here I want to select only maximum path . Here I used "SYS_CONNECT_BY_PATH"
    Please let meknow how to do this ?
    Thanks in advance .
    Edited by: udeffcv on Dec 9, 2009 10:03 PM

    udeffcv wrote:
    Hi all,
    I got the result with the hierarchical query as :
    */qxxh*
    */qxxh/jxobcbg*
    */qxxh/jxobcbg/n00wcp4*
    */qxxh/jxobcbg/n00wcp4/x000263*
    */qxxh/jxobcbg/n00wcp4/x000263/p0263*
    */qxxh/jxxocbg*
    */qxxh/jxxocbg/n00voc1*
    */qxxh/jxxocbg/n00voc1/x000589*
    */qxxh/jxxocbg/n00voc1/x000589/p0589*
    */qxxh/jxuwxxh*
    */qxxh/jxuwxxh/n00xpxf*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl/x000522*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl/x000522/p0522*
    Here I want to select only maximum path . Here I used "SYS_CONNECT_BY_PATH"
    Please let meknow how to do this ?
    Thanks in advance .
    Edited by: udeffcv on Dec 9, 2009 10:03 PMwhat do you mean by maximum path?? is it...
    */qxxh/jxobcbg/n00wcp4/x000263/p0263*
    */qxxh/jxxocbg/n00voc1/x000589/p0589*
    */qxxh/jxuwxxh/n00xpxf/m00bxpl/x000522/p0522*
    is it child nodes??
    then you might like to see
    CONNECT_BY_ISLEAF pseudo column..example you can find it in below link
    http://download.oracle.com/docs/cd/B14117_01/server.101/b10759/pseudocolumns001.htm#sthref670
    Ravi Kumar

  • Help for hierarchical query

    Hi all,
    I must be tired and cannot think clearly, so I'm a bit confused the following query.
    The environment is still Oracle 9i:
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    PL/SQL Release 9.2.0.8.0 - Production
    CORE    9.2.0.8.0    Production
    TNS for HPUX: Version 9.2.0.8.0 - Production
    NLSRTL Version 9.2.0.8.0 - Production
    Suppose that I have the following data:
    with mydata as
       select 1 code, null code_high, 'John' cname, 'Smith'   csurname, 'X'   resp from dual union all
       select 2 code, 1    code_high, 'Bill' cname, 'White'   csurname, null  resp from dual union all
       select 3 code, 2    code_high, 'Fred' cname, 'Reed'    csurname, 'X'   resp from dual union all
       select 4 code, null code_high, 'Tim'  cname, 'Hackman' csurname, 'X'   resp from dual union all
       select 5 code, 4    code_high, 'John' cname, 'Reed'    csurname, null  resp from dual union all
       select 6 code, 5    code_high, 'Bill' cname, 'Hakcman' csurname, 'X'   resp from dual union all
       select 7 code, 6    code_high, 'Fred' cname, 'White'   csurname, null  resp from dual union all
       select 8 code, 7    code_high, 'Bill' cname, 'Smith'   csurname, null  resp from dual union all
       select 9 code, 8    code_high, 'Tom'  cname, 'Reed'    csurname, null  resp from dual
    select *
       from mydata;
          CODE  CODE_HIGH CNAME CSURNAME RESP
             1            John  Smith    X  
             2          1 Bill  White       
             3          2 Fred  Reed     X  
             4            Tim   Hackman  X  
             5          4 John  Reed        
             6          5 Bill  Hakcman  X  
             7          6 Fred  White       
             8          7 Bill  Smith       
             9          8 Tom   Reed        
    This is a hierarchical query where code_high represent the father.
    I need to find in the hierarchy the upper responsible level for each code.
    Suppose that I want to find in the hierarchy the first one having resp='X'.
    Running the following query I can find it for code = 9
    select code, cname, csurname
       from mydata
      where resp = 'X'
       and rownum = 1
    connect by prior code_high = code
      start with code = 9;
          CODE CNAME CSURNAME
             6 Bill  Hakcman
    Is there a way to get the whole list with the corresponding responsible.
    Here is the expected output:
          CODE  CODE_HIGH CNAME CSURNAME RESP RESP_CODE RESP_NAME RESP_SURNAME
             1            John  Smith    X            1 John      Smith  
             2          1 Bill  White                 1 John      Smith  
             3          2 Fred  Reed     X            3 Fred      Reed   
             4            Tim   Hackman  X            4 Tim       Hackman
             5          4 John  Smith                 4 Tim       Hackman
             6          5 Bill  Hakcman  X            6 Bill      Hakcman
             7          6 Fred  White                 6 Bill      Hakcman
             8          7 Bill  Smith                 6 Bill      Hakcman
             9          8 Tom   Reed                  6 Bill      Hakcman
    Regards.
    Alberto

    Hi Anar,
    check my post and my expected output.
    This is too simple and it is not what I need.
    Your code is showing this output:
            SS       CODE CNAME CSURNAME RESP
             1          1 John  Smith    X  
             1          3 Fred  Reed     X  
             1          4 Tim   Hackman  X  
             1          6 Bill  Hakcman  X  
    Actually the only way I have found (in Oracle 9i) is the following:
    select code, code_high, cname, csurname, resp
         , ( select code
               from mydata
              where resp='X'
                and rownum=1
            connect by prior code_high = code
            start with code=a.code
           ) resp_code
         , ( select cname
               from mydata
              where resp='X'
                and rownum=1
            connect by prior code_high = code
            start with code=a.code
           ) resp_name
         , ( select csurname
               from mydata
              where resp='X'
                and rownum=1
            connect by prior code_high = code
            start with code=a.code
           ) resp_surname
      from mydata a;
          CODE  CODE_HIGH CNAME CSURNAME RESP  RESP_CODE RESP_NAME RESP_SURNAME
             1            John  Smith    X             1 John      Smith      
             2          1 Bill  White                  1 John      Smith      
             3          2 Fred  Reed     X             3 Fred      Reed       
             4            Tim   Hackman  X             4 Tim       Hackman    
             5          4 John  Reed                   4 Tim       Hackman    
             6          5 Bill  Hakcman  X             6 Bill      Hakcman    
             7          6 Fred  White                  6 Bill      Hakcman    
             8          7 Bill  Smith                  6 Bill      Hakcman    
             9          8 Tom   Reed                   6 Bill      Hakcman    
    But I don't like this.
    Regards.
    Alberto

  • Hierarchical query to combine two groupings into one broad joint grouping

    Hi there,
    I would like to know if anyone knows a way to solve the problem below with a SQL querie, maybe using some hierarchical queries or window functions (or anything else in SQL for that matter).
    My environment is:
    Oracle Database 11g Release 11.2.0.2.0 - 64bit
    The problem is this:
    I have a list of items that are grouped together in two different grouping ways (two columns).
    This gives the ability for items to be linked to other items in two ways:
    1. Directly if both have same value on GROUP1 and/or GROUP2;
    2. indirectly if they have an item in common with at least one match on either GROUP1 or GROUP2.
    The idea is to start from this dataset:
    WITH T AS
      SELECT 1 AS ITEM_ID, 'A' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
      SELECT 2 AS ITEM_ID, 'A' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
      SELECT 3 AS ITEM_ID, 'A' AS GROUP1, 101 AS GROUP2 FROM DUAL UNION
      SELECT 4 AS ITEM_ID, 'B' AS GROUP1, 100 AS GROUP2 FROM DUAL UNION
      SELECT 5 AS ITEM_ID, 'B' AS GROUP1, 102 AS GROUP2 FROM DUAL UNION
      SELECT 6 AS ITEM_ID, 'C' AS GROUP1, 103 AS GROUP2 FROM DUAL UNION
      SELECT 7 AS ITEM_ID, 'D' AS GROUP1, 101 AS GROUP2 FROM DUAL
    SELECT * FROM T;
    And end up with this dataset with a one single joint grouping:
    WITH T AS
      SELECT 1000 AS JOINT_GROUP_ID, 1 AS ITEM_ID FROM DUAL UNION
      SELECT 1000 AS JOINT_GROUP_ID, 2 AS ITEM_ID FROM DUAL UNION
      SELECT 1000 AS JOINT_GROUP_ID, 3 AS ITEM_ID FROM DUAL UNION
      SELECT 1000 AS JOINT_GROUP_ID, 4 AS ITEM_ID FROM DUAL UNION
      SELECT 1000 AS JOINT_GROUP_ID, 5 AS ITEM_ID FROM DUAL UNION
      SELECT 1000 AS JOINT_GROUP_ID, 7 AS ITEM_ID FROM DUAL UNION
      SELECT 2000 AS JOINT_GROUP_ID, 6 AS ITEM_ID FROM DUAL
    SELECT * FROM T;The relationships are:
    Item 1 is linked to Item 2 by GROUP1 and GROUP2;
    Item 1 is linked to Item 3 by GROUP1 only;
    Item 1 is linked to Item 4 by GROUP2 only;
    Item 1 is linked to Item 5 through Item 4 by GROUP1;
    Item 1 is linked to Item 7 through Item 3 by GROUP2;
    Item 6 is not linked to any other item since it does not match on GROUP1 nor GROUP2 with any other item.
    NOTEs:
    - JOINT_GROUP_ID values could be any sequential value. I used 1000 and 2000 just to avoid confusion with the other IDs and group values used to picture the problem.
    - The level of relationship is not restricted to 2 like the example above. There could be deeper relationships.
    This seems to me like something that could be solved with a hierarchical query, but I could not get my head around it to solve the problem.
    Hope one of you guys can help me on this.
    Chears.

    Hi Bruno,
    You are correct. Frank's solution does not work. You can do this using CONNECT BY on smaller problems, but it will be very inefficient for larger problems wirth significant looping. I wrote a quick blog article on this subject after reading your question this morning. This is actually an example of a very general class of problems and I already had three SQL solutions. I'll put the CONNECT BY one here, and you can look at my blog if you want more details (I include a diagram so I can't just post it here).
    Data
    item_groups
    SQL> SELECT *
      2    FROM item_groups
      3  /
    ITEM_ID    GROUP1                         GROUP2
    01         A                              100
    02         A                              100
    03         A                              101
    04         B                              100
    05         B                              102
    06         C                              103
    07         D                              101
    08         E                              104
    09         E                              105
    10         F                              106
    10 rows selected.Query
    WITH links_v AS (
    SELECT t_fr.item_id node_id_fr,
           t_to.item_id node_id_to,
           t_fr.item_id || '-' || Row_Number() OVER (PARTITION BY t_fr.item_id ORDER BY t_to.item_id) link_id
      FROM item_groups t_fr
      JOIN item_groups t_to
        ON t_to.item_id > t_fr.item_id
       AND (t_to.group1 = t_fr.group1 OR t_to.group2 = t_fr.group2)
    ), nodes_v AS (
    SELECT item_id node_id
       FROM item_groups
    ), tree AS (
    SELECT link_id, CONNECT_BY_ROOT (link_id) root_id
      FROM links_v
    CONNECT BY NOCYCLE (node_id_fr = PRIOR node_id_to OR node_id_to = PRIOR node_id_fr OR
                         node_id_fr = PRIOR node_id_fr OR node_id_to = PRIOR node_id_to)
    ), group_by_link AS (
    SELECT DISTINCT Min (root_id) OVER (PARTITION BY link_id) group_id, link_id
      FROM tree
    ), linked_nodes AS (
    SELECT g.group_id, l.node_id_fr node_id
      FROM group_by_link g
      JOIN links_v l
        ON l.link_id = g.link_id
    UNION
    SELECT g.group_id, l.node_id_to
      FROM group_by_link g
      JOIN links_v l
        ON l.link_id = g.link_id
    SELECT l.group_id "Network", l.node_id "Node"
      FROM linked_nodes l
    UNION ALL
    SELECT '00 (unlinked)', node_id
      FROM nodes_v n
    WHERE n.node_id NOT IN (SELECT node_id FROM linked_nodes)
    ORDER BY 1, 2Output
    Network       Node
    00 (unlinked) 06
                  10
    01-1          01
                  02
                  03
                  04
                  05
                  07
    08-1          08
                  09

  • Hierarchical Query Help

    Version: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    Hello,
    I'm hoping I can get help with a Hierarchical Query.
    My base table contains Projects with a Group ID. Each Group can have the same Project Name so displaying the information in a Select List on an form for data entry can be very confusing. I'm hoping I can get a query that would produce the output below.
    Please let me know if I haven't provided the necessary information.
    The tables involved are:
    CREATE TABLE projects
      PROJECT_ID             NUMBER,
      PROJECT_NAME           VARCHAR2(100),
      GROUP_ID               NUMBER
    CREATE TABLE vertical_group
      GROUP_ID      NUMBER,
      GROUP_NAME    VARCHAR2(50)
    The data is:
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (1,'Proj Grp 1',1);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (2,'Proj Grp 1',1);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (3,'Proj Grp 1',1);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (4,'Proj Grp 1',1);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (5,'Proj Grp 1',1);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (6,'Proj Grp 2',2);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (7,'Proj Grp 2',2);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (8,'Proj Grp 2',2);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (9,'Proj Grp 2',2);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (10,'Proj Grp 3',3);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (11,'Proj Grp 3',3);
    INSERT INTO projects(project_id,project_name,group_id)
    VALUES (12,'Proj Grp 3',3);
    INSERT INTO vertical_group(group_id,group_name)
    VALUES (1,'Group 1');
    INSERT INTO vertical_group(group_id,group_name)
    VALUES (2,'Group 2');
    INSERT INTO vertical_group(group_id,group_name)
    VALUES (3,'Group 3');
    The desired output is:
    Group 1
        Proj Grp 1
        Proj Grp 1
        Proj Grp 1
        Proj Grp 1
        Proj Grp 1
    Group 2
        Proj Grp 2
        Proj Grp 2
        Proj Grp 2
        Proj Grp 2
    Group 3
        Proj Grp 3
        Proj Grp 3
        Proj Grp 3
    Thanks,
    Joe

    No hierarchical query is needed. Use UNION ALL and weights:
    with t as (
                select  'Group ' || group_id name,
                        group_id,
                        1 weight
                  from  projects
                  group by group_id
               union all
                select  '  ' || project_name,
                        group_id,
                        2 weight
                  from  projects
    select  name
      from  t
      order by group_id,
               weight,
               name
    NAME
    Group 1
      Proj Grp 1
      Proj Grp 1
      Proj Grp 1
      Proj Grp 1
      Proj Grp 1
    Group 2
      Proj Grp 2
      Proj Grp 2
      Proj Grp 2
      Proj Grp 2
    NAME
    Group 3
      Proj Grp 3
      Proj Grp 3
      Proj Grp 3
    15 rows selected.
    SQL>
    SY.

  • CONTAINS in hierarchical query

    Hello friends!
    I have a table that describes some tree:
    CATEGORIES (cat_id NUMBER, parent_id NUMBER, title VARCHAR2,
    description VARCHAR2);
    The following query works fast:
    SELECT count(*)
    FROM categories
    WHERE CONTAINS( title,'Moscow WITHIN description OR Moscow
    WITHIN title', 1 ) > 0;
    But the hierarchical query
    SELECT count(*)
    FROM categories
    WHERE CONTAINS( title, 'Moscow WITHIN description OR Moscow
    WITHIN title', 1 ) > 0
    START WITH cat_id = 1 CONNECT BY PRIOR cat_id = parent_id;
    works very slowly.
    What&#8217;s wrong and what should I do?
    Thank you!
    Index is:
    begin
    ctx_ddl.create_preference('cat_lexer', 'BASIC_LEXER');
    ctx_ddl.set_attribute ('cat_lexer', 'printjoins', '_-');
    ctx_ddl.set_attribute ('cat_lexer', 'index_themes', 'NO');
    ctx_ddl.set_attribute ('cat_lexer', 'index_text', 'YES');
    end;
    exec ctx_cd.Create_CDstore('categories_cdstore', 'categories')
    exec ctx_cd.Add_Column ('categories_cdstore', 'title')
    exec ctx_cd.Add_Column ('categories_cdstore', 'description')
    create index categ_title_index on categories( title ) INDEXTYPE
    IS ctxsys.context
    PARAMETERS ('LEXER cat_lexer DATASTORE categories_cdstore
    SECTION GROUP categories_cdstore MEMORY 50M');

    Thank you Thomas,
    I tried to use subquery like this:
    SELECT count(*)
    FROM (SELECT cat_id, title, description
    FROM categories
    START WITH cat_id = 2 CONNECT BY PRIOR cat_id =
    parent_id) c
    WHERE CONTAINS( c.title,'Moscow WITHIN description OR Moscow
    WITHIN title', 1 ) > 0;
    It works more faster <0.5-1 min.> then that in my first post <5-
    7 min.>, but still slow than I wish.
    If I use normal index (WHERE title LIKE '%Moscow%' AND ...) the
    answer is immediate in this query!!! Yo!
    Is this an Oracle's bag or mine?
    Indeed, I try to solve more complex task.
    I have another table RESOURCES (cat_id, url, title) that is
    detail of CATEGORIES table. Assosiation one-to-many
    categories.cat_id = resources.cat_id.
    SELECT COUNT(*)
    FROM resources r, (
         SELECT cat_id
         FROM     categories
         START     WITH cat_id = 2 CONNECT BY PRIOR cat_id =
    parent_id) c
    WHERE c.cat_id = r.cat_id
    AND CONTAINS(title,'Moscow',2)>0;
    Again this works more slowly than if I use NORMAL index.

  • Hierarchical query - How to get all parent records - Duplicate post

    Hi,
    In Oracle, START WITH, CONNECT BY commands will give all the direct and indirect child records. Other way round, is they are command which gives all the parent records till the root? Please let me know. I am working on Oracle 9i Release 2.
    Thanks a lot for your help.
    Edited by: skv on Nov 21, 2008 11:05 AM

    Duplicate post.
    Hierarchical query - How to get all parent records
    Please edit this post heading to duplicate post.
    Regards.
    Satyaki De.

Maybe you are looking for