Hierarchical sql-how to get only branches with at least one not null leaves

On 10gR2 we want below hierarchical query to return only the branches which at least have one not NULL leaf ;
-- drop table corporate_slaves purge ;
create table corporate_slaves (
slave_id integer primary key,
supervisor_id references corporate_slaves,
name varchar(100), some_column number );
insert into corporate_slaves values (1, NULL, 'Big Boss ', NULL);
insert into corporate_slaves values (2, 1, 'VP Marketing', NULL);
insert into corporate_slaves values (9, 2, 'Susan ', NULL);
insert into corporate_slaves values (10, 2, 'Sam ', NULL);
insert into corporate_slaves values (3, 1, 'VP Sales', NULL);
insert into corporate_slaves values (4, 3, 'Joe ', NULL);
insert into corporate_slaves values (5, 4, 'Bill ', 5);
insert into corporate_slaves values (6, 1, 'VP Engineering', NULL);
insert into corporate_slaves values (7, 6, 'Jane ', NULL);
insert into corporate_slaves values (8, 6, 'Bob' , 3);
SELECT sys_connect_by_path(NAME, ' / ') path, some_column col,  connect_by_isleaf isLeaf
  FROM corporate_slaves
CONNECT BY PRIOR slave_id = supervisor_id
START WITH slave_id IN
            (SELECT slave_id FROM corporate_slaves WHERE supervisor_id IS NULL) ;For this example wanted output is like this one since Marketing has no NOT NULL some_column leaves where as Engineering and Sales has at least one;
PATH                                                                            
/ Big Boss                                                                  
/ Big Boss  / VP Sales                                                      
/ Big Boss  / VP Sales / Joe                                                
/ Big Boss  / VP Sales / Joe  / Bill                                        
/ Big Boss  / VP Engineering                                                
/ Big Boss  / VP Engineering / Jane                                         
/ Big Boss  / VP Engineering / Bob                                           Regards.

Here is a slightly modified version, you can try it:
WITH SRC AS (
SELECT   SYS_CONNECT_BY_PATH(NAME ,
                             '/ ') path,
         SOME_COLUMN COL,
         CONNECT_BY_ISLEAF ISLEAF,
         CONNECT_BY_ROOT SLAVE_ID ROOT_SLAVE_ID,
         SLAVE_ID slave_id,
         CONNECT_BY_ROOT SUPERVISOR_ID SUPERVISOR_ID,
         SOME_COLUMN
    FROM CORPORATE_SLAVES
  CONNECT BY PRIOR SLAVE_ID = SUPERVISOR_ID
SELECT path, col, isleaf
FROM SRC
WHERE SUPERVISOR_ID IS NULL
AND SLAVE_ID IN (SELECT ROOT_SLAVE_ID FROM SRC WHERE SOME_COLUMN IS NOT NULL)
PATH                                COL                    ISLEAF                
/ Big Boss                                                 0                     
/ Big Boss / VP Sales                                      0                     
/ Big Boss / VP Sales/ Joe                                 0                     
/ Big Boss / VP Sales/ Joe / Bill   5                      1                     
/ Big Boss / VP Engineering                                0                     
/ Big Boss / VP Engineering/ Bob    3                      1                     
6 rows selectedI tested it for 1000 records in the source table (tested on Oracle 10 XE),
and .... the performance was a big surprise:
INSERT INTO corporate_slaves
SELECT SLAVE_ID + X SLAVE_ID,
       SUPERVISOR_ID + X SUPERVISOR_ID,
       NAME || ' ' || X NAME,
       some_column
FROM  CORPORATE_SLAVES
CROSS JOIN (
  SELECT 10*LEVEL x
  FROM DUAL
  CONNECT BY LEVEL <= 100
COMMIT;
SELECT count(*) FROM corporate_slaves;
COUNT(*)              
1010 Your query (slightly modified - removed leading space from the separator in CONNECT_BY_PATH):
set timings on;
CREATE TABLE BUBA1 AS
SELECT SYS_CONNECT_BY_PATH(NAME,
                            '/ ') path,
        some_column col,
        connect_by_isleaf isleaf
    FROM corporate_slaves
   WHERE slave_id IN (SELECT connect_by_root slave_id "slave_id"
                        FROM corporate_slaves
                       WHERE some_column IS NOT NULL
                      CONNECT BY PRIOR slave_id = supervisor_id)
  CONNECT BY PRIOR slave_id = supervisor_id
   START WITH SLAVE_ID IN
              (SELECT SLAVE_ID FROM CORPORATE_SLAVES WHERE SUPERVISOR_ID IS NULL)
CREATE TABLE succeeded.
6 095ms elapsedrewritten query:
CREATE TABLE BUBA2 AS
WITH SRC AS (
SELECT   SYS_CONNECT_BY_PATH(NAME ,
                             '/ ') path,
         SOME_COLUMN COL,
         CONNECT_BY_ISLEAF ISLEAF,
         CONNECT_BY_ROOT SLAVE_ID ROOT_SLAVE_ID,
         SLAVE_ID slave_id,
         CONNECT_BY_ROOT SUPERVISOR_ID SUPERVISOR_ID,
         SOME_COLUMN
    FROM CORPORATE_SLAVES
  CONNECT BY PRIOR SLAVE_ID = SUPERVISOR_ID
SELECT path, col, isleaf
FROM SRC
WHERE SUPERVISOR_ID IS NULL
AND SLAVE_ID IN (SELECT ROOT_SLAVE_ID FROM SRC WHERE SOME_COLUMN IS NOT NULL)
CREATE TABLE succeeded.
167ms elapsed
SELECT COUNT(*) FROM BUBA1;
COUNT(*)              
606 
SELECT COUNT(*) FROM BUBA2;
COUNT(*)              
606
SELECT COUNT(*) FROM(
  SELECT * FROM BUBA1
  INTERSECT
  SELECT * FROM BUBA2
COUNT(*)              
606  ANd now the above tests repeated for 10.000 records
truncate table  corporate_slaves;
insert into corporate_slaves values (1, NULL, 'Big Boss ', NULL);
insert into corporate_slaves values (2, 1, 'VP Marketing', NULL);
insert into corporate_slaves values (9, 2, 'Susan ', NULL);
insert into corporate_slaves values (10, 2, 'Sam ', NULL);
insert into corporate_slaves values (3, 1, 'VP Sales', NULL);
insert into corporate_slaves values (4, 3, 'Joe ', NULL);
insert into corporate_slaves values (5, 4, 'Bill ', 5);
insert into corporate_slaves values (6, 1, 'VP Engineering', NULL);
insert into corporate_slaves values (7, 6, 'Jane ', NULL);
insert into corporate_slaves values (8, 6, 'Bob' , 3);
INSERT INTO corporate_slaves
SELECT SLAVE_ID + X SLAVE_ID,
       SUPERVISOR_ID + X SUPERVISOR_ID,
       NAME || ' ' || X NAME,
       some_column
FROM  CORPORATE_SLAVES
CROSS JOIN (
  SELECT 10*LEVEL x
  FROM DUAL
  CONNECT BY LEVEL <= 1000
COMMIT;
SELECT count(*) FROM corporate_slaves;
COUNT(*)              
10010
CREATE TABLE BUBA22 AS
WITH SRC AS (
SELECT   SYS_CONNECT_BY_PATH(NAME ,
                             '/ ') path,
         SOME_COLUMN COL,
         CONNECT_BY_ISLEAF ISLEAF,
         CONNECT_BY_ROOT SLAVE_ID ROOT_SLAVE_ID,
         SLAVE_ID slave_id,
         CONNECT_BY_ROOT SUPERVISOR_ID SUPERVISOR_ID,
         SOME_COLUMN
    FROM CORPORATE_SLAVES
  CONNECT BY PRIOR SLAVE_ID = SUPERVISOR_ID
SELECT path, col, isleaf
FROM SRC
WHERE SUPERVISOR_ID IS NULL
AND SLAVE_ID IN (SELECT ROOT_SLAVE_ID FROM SRC WHERE SOME_COLUMN IS NOT NULL)
CREATE TABLE succeeded.
345ms elapsed
CREATE TABLE BUBA11 AS
SELECT SYS_CONNECT_BY_PATH(NAME,
                            '/ ') path,
        some_column col,
        connect_by_isleaf isleaf
    FROM corporate_slaves
   WHERE slave_id IN (SELECT connect_by_root slave_id "slave_id"
                        FROM corporate_slaves
                       WHERE some_column IS NOT NULL
                      CONNECT BY PRIOR slave_id = supervisor_id)
  CONNECT BY PRIOR slave_id = supervisor_id
   START WITH SLAVE_ID IN
              (SELECT SLAVE_ID FROM CORPORATE_SLAVES WHERE SUPERVISOR_ID IS NULL)
CREATE TABLE succeeded.
526 437ms elapsed
SELECT COUNT(*) FROM BUBA11;
COUNT(*)              
6006
SELECT COUNT(*) FROM BUBA22;
COUNT(*)              
6006
SELECT COUNT(*) FROM(
  SELECT * FROM BUBA11
  INTERSECT
  SELECT * FROM BUBA22
COUNT(*)              
6006 Wow.... 526 seconds vs. 0,4 seconds !!!
131500 % performance gain ;)
I have got similar results on Oracle 11.2

Similar Messages

  • How to get PO list with mark archived or not?

    Hi experts,
    I have a list of POs from both database and archive server using standard report ME2N but I can't distinguish between archived PO or not.
    Actually if I checked the detail PO I could see if it was from archive or not, but this way takes time.
    Please advise how to get list of PO with mark from archive or database.
    Thanks.
    rob

    hi
    u can use me82
    or in me2n us the scope as ARCHIV
    regards
    kunal

  • How to get  Unapplied Amount with SQL or API in AR/ORACLE RECEIVABLES

    Hi ,
    how to get Unapplied Amount with SQL or API in AR/ORACLE RECEIVABLES.
    who can help me ? Thank you very much !

    i get it from private API.
    SELECT SUM(decode(ra.status, 'UNAPP', nvl(ra.amount_applied, 0), 0)) unapplied_amount
    FROM ar_receivable_applications ra
    WHERE ra.cash_receipt_id = 1820
    AND ra.status IN ('UNAPP', 'ACTIVITY')

  • I lost my iphone, got a new sim card and put it in my boyfriend's old iphone. When I synch it in itunes it will only synch with his stuff and not mine. Any ideas how I can get it to synch with my itunes??

    I lost my iphone, got a new sim card and put it in my boyfriend's old iphone. When I synch it in itunes it will only synch with his stuff and not mine. Any ideas how I can get it to synch with my itunes??

    Are you using a Mac? It sounds like you are using his computer to sync to. If this is the case, then it will sync to all of his stuff unless a new user is created with your personal stuff on it.
    When you want to sync your iPhone to that computer, switch to your user first, and then everything will sync with your stuff. If he wants to hook up his iPhone to sync it, then he needs to switch back to his own username first.

  • My husband wiped out the library on his itunes account and replaced it with mine.  Any ideas on how to get it back?  Our laptop does not have his library either.  only mine.

    My husband wiped out the library on his itunes account and replaced it with mine.  Any ideas on how to get it back?  Our laptop does not have his library either.  only mine. 

    How exactly did this happen? Were you using separate iTunes libraries on separate user accounts on the laptop?
    B-rock

  • How to get only current exception message from tables

    Hi
    In my sceanario , I want to have the list of Current MRP exception messages list from table
    I understand that MRP detailed lists, including all exception messages, are stored in transparent table MDKP and cluster table MDTC.
    I can tell ABAPer to write a report for me , to read the data from these tables , but I guess these tables contain old exception message also , which are not currently appearing in MRP list
    How to get only current exception message
    Rgds,
    sandeep

    Sandeep,
    MDTC contains only data from the most recent MRP run.  So, all messages you see are those which are currently valid.
    The messages might have first appeared during a previous run, but they still need to be addressed.
    Before you invest a lot of time and effort into writing and debugging a custom report, you should probably try to use the standard SAP functionality found in MD06.  On the Processing indicator tab, you can select "Only with new exceptions".  Here you can tag a material/plant as 'processed', and thereafter, the exceptions that existed there before you tagged the part will not be re-displayed.
    Best Regards,
    DB49

  • How to get the itunes with those 3 colored buttons on top left corner ????ner ???

    Please help [humble request] ----
    I have 3 problems can u please help me out --
    1) How to get the itunes with the 3 colored buttons (i'm new to apple ,just 8 days so i dont know much stuff) on top left corner ,i've downloaded thrice from apple's site directly i everytime got the same sort of itunes with 'File' ,'Edit' ,'View' ,'Controls' ,'Store' ,'Adanced' ,'Help' on the top ,and also whenever i open the itunes store (in this itunes) only the app store opens ,now music albums ,movies ,tv shows nothing !!
    2) I dont know how to import video files from the computer to itunes
    3)i bought an app [fifa 11] ,n downloaded another 1 [contract killer] {ive deleted them and downloaded them thrice ,and they dont sync to my itouch it shows error (0xE800004C)
    Please please please help me im getting worried and frustrated
    please help me out with this

    but illaass
    i asked 2 of my frnds both of them have windows n not mac ,both of them are sayin dat they have the coloured buttons one , and i asked them dat how to access the itunes music store they said that when they kliked d itunes store option in the left side a screen appears where 6 -7 categories are there which are music store ,app store ,podcasts ,movies ,tv shows etc . bt when i open it it only shows d app store ,and on the bar only 4 options are ther the home icon , app store , podcasts and itunes u ,and when i klik movies ,tv shows on the left side ,there is an option "browse for movies in the itunes store" i klik it and only the app store opens and nothing else .
    and thanks now i know how to import videos
    and sigma 1337 ,
    ive downloaded the apps 4 -5 times now , still d same error mssg it comes like dis :-
    " Some of the apps in your iTunes library were not installed on the ipod "Shomik's ipod" because one or more errors occurred "
    please help me  im gettin frustrated

  • How to get applets running with Java Plug-in on Win but also on Mac OS X???

    I've converted to the use of Java Plug-in for my applets, but I need to have those same applets executable from browsers on Mac OS X platform. Surely this has been done, but I don't see how. The browsers I've tried on Mac OS X (Netscape, IE) don't seem to recognize the <OBJECT> tag used for the java plug-in. I've seen no news about the Java plug-in being ported to Macs. How can one get the same applet to run with the Java plug-in on Windows browsers, and also to run with at least one of the common browsers on Mac OS X? Any help would be SO much appreciated!

    Those ten dukes look good to me. But the passing of fifteen months has me thinking you've probably moved on. In any case, here's my effort.
    I've been through a trial trying to get my applet, developed with 1.4.1_03, to run on my Mac OS X v.10.2.6 in multiple browsers. I'm posting my results here. Comments and feedback are welcome.
    JVM support for 1.4.1 is limited to the Safari browser. All other browsers running in Mac OS X that I've tried ( Camino, Opera, Internet Explorer, Mozilla ) are using the 1.3.1 plugin. According to a bug report by Mozilla on this topic ( see Bugzilla Bug # 197813 http://bugzilla.mozilla.org/show_bug.cgi?id=197813 )
    with the release of Apple's version of Sun's Java 1.4.1 the applet programming model has changed, and only Safari has adapted with this change. Other browsers, according to the report, could not because of a lack of documentation. The use of the MRJCarbon plugin offered by Mozilla (here - http://www.mozilla.org/oji/MRJPluginCarbon.html) only allows Mozilla to use the J 1.3.1. And I have not found any information on the Microsoft site about how to get IE 5.2 to recognize the newer version of Java.
    Regarding the use of the OBJECT tag in Safari, it is a matter of debate. A current post on this topic exists in the Applet Development forum:
    http://forum.java.sun.com/thread.jsp?forum=421&thread=441002
    In my experience, I have not been able to determine that Safari v1.0 recognizes the OBJECT tag. My experience is that the APPLET tag is required to run applets in Safari. The Bugzilla report echoes the problem with the BadMagicNumber error that can arise in Safari. Nonetheless, I enjoy Safari and I enjoy Mac OS X.

  • How to get ALV Display with First column alone in sort

    How to get ALV Display with First column alone in sort

    HI,
    You can build Internal Table and send this to the parameter "IT_SORT".
    eg:
    "the sorting Internal Table structure is as whown below.
    DATA:  t_sort_info type slis_t_sortinfo_alv.
    "Build the Sort Internal Table
      t_sort_info-fieldname = 'CARRID'.
      t_sort_info-subtot = 'X'.
      append t_sort_info.
      t_sort_info-fieldname = 'FLDATE'.
      t_sort_info-subtot = 'X'.
      append t_sort_info.
    Then pass this "IT_SORT_INFO" table to the Function module "Reuse_alv_*". (Note send the body of the Internal table only like "<b>IT_SORT = IT_SORT_INFO[]</b>".
    Here i am making ALV output sorted on CARRID & FLDATE.
    You can specify only the First Column name for sorting.
    Regards,
    Manju
    Message was edited by:
            MANJUNATHA KS

  • 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.

  • How to get spool along with e-mail or FAX

    Hi,
    I have a requirement where i have to produce a spool even i go for e-mail or FAX option when the script is triggered.
    I am using a standard program where it is coded to have either of the option. i.e. either we have to go for a printer or e-mail or FAX.
    Could any one suggest me how to get spool along with e-mail or FAX option.
    Thanks in advance.

    Hi,
    check this:-[http://help.sap.com/saphelp_nw04/helpdata/en/a5/28d3b9d26211d4b646006094192fe3/frameset.htm]
    hope u'll get some idea.
    Regards,
    Sneha.

  • In Table Control How to get only a single row .

    Hi
    In Table Control How to get only a single row .I am able to decrease it its height to 4 but then 2 rows is getting dsplayed .I want only one row to be display and 2nd row should be deactivated or not visible.
    regards
    Avik
    Edited by: Julius Bussche on Jan 30, 2009 1:10 PM
    Removed friendly greeting from the subject title

    Hi Avik
    use this code it will help you.
    MODULE passdata OUTPUT.
      READ TABLE it_revision INTO wa_rev INDEX tab_clc-current_line.
      IF sy-subrc = 0.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.      " 111 IS THE GROUP NAME
            screen-input = 1.          " input mode
            screen-active = 1.         " input mode.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ELSE.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.       "GROUP NAME
            screen-input = 0.           " display mode
            screen-active = 1.          " DISPLAY MODE.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ENDIF.
    ENDMODULE.                 " PASSDATA  OUTPUT
    Make sure in group tou are passing the field name that you want in input mode on the base of other field
    Hope it will help you.
    Thanks
    Arun Kayal.

  • How To Get Only Month or Only Year from datetime format of yyyy-mm-dd

    Hi SQL gurus,
    I have field has datetime format of yyyy-mm-dd (ie. 2014-11-28).  Could anyone please educate me on how to extract only month (ie. November but not 11) and only year (ie, 2014) from 2014-11-28.  I writing two report have title of Number of
    sick leaves on November  and Number of sick leaves in 2014.  I am planning to extact 11 from 2014-11-28 and display as November on report title and the same goes for 2014.  Unless you have better non complicated way.   Thank you
    very much in advance.  DingDong!!

    There are multiple ways
    Month name
    SELECT DATENAME(mm,@DateParam)
    SELECT FORMAT(@DateParam,'MMMM')
    Year
    SELECT FORMAT(@DateParam,'yyyy')
    SELECT DATEPART(yy,@DateParam)
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • I have a problem with mail.  the spelling and grammer check box before sending the messege is no longer there.  I did everything but cannot get it back.  is ther anyone who knows how to get the box with spelling and grammer checks before sending

    i have a problem with mail.  the spelling and grammer check box before sending the messege is no longer there.  I did everything but cannot get it back.  is ther anyone who knows how to get the box with spelling and grammer checks before sending the mail.
    Also the mail is acting very funny by not getting the rules work in a proper method.  Is ther a software to repair mail.

    i did both of them, but still the while sending the mail the diolog box is not showing up and also the spelling and grammer does not do the spelling check. 
    This problem just started for about 3 to 4 days now.  earlier it was working normally.

  • How to get the table with no. of records after filter in webdynpro

    Dear Gurus,
    How to get the table with no. of records after filter in webdynpro?
    Thanks in advance.
    Sankar

    Hello Sankar,
    Please explain your requirement clearly so that we can help you easily.
    To get the table records from your context node use method get_static_attributes_table()
    data lo_nd_mynode       type ref to if_wd_context_node. 
    data lt_atrributes_table  type wd_this->elements_mynode. 
    lo_nd_mynode = wd_context->get_child_node( name = wd_this->wdctx_mynode ). 
    lo_nd_mynode->get_static_attributes_table( importing table = lt_atrributes_table ). 
    Note: You should have already defined your context node as a Dictionary Structure.
    BR,
    RAM

Maybe you are looking for

  • Safari won't launch on OS X 10.8.5

    Macbook Pro OS X 10.8.5 2.5 GHz Intel Core i5 4GB 1600 MHz DDR3 Safari won't properly open after the system update. It bounces on the dock for a few seconds and nothing happens. When you click a few times, it crashes. However, it works fine on safe m

  • ABS as a router?

    Wondering if I can use my white dual ABS as a router and an ABS? I now have a NDAS drive that will not operate with two things running DHCP (ABS and LINKSYS Router) So I would like to use my ABS as a router and airport. I thought at one time I read s

  • 4.6C FI-FM Payment transfer settings.

    Hi, everyone! Can you give me an advice – whether it is possible to change settings of Payment transfer program (RFFMS200) from “S200 Original Functions” to “S200 Enhanced Function”, considering that there are actual postings already recorded in the

  • InDesign Code

    We developed a catalog using InDesign. Can these files be converted to an excel format to import in a Magento Data Base

  • IPHONE: PROBLEM SENDING EMAILS IN/OUT OF HOME ISP'S NETWORK

    THE PROBLEM: Some Home ISPs won't allow their users to use the same SMTP port when they are inside or outisde their Network to send an email of their ISP's domain ([email protected]). This prevents the iPhone user from being able to send emails flawl