How to order a tree balanced with SQL hierarchical queries

by searching the forum I found this

Re: Generate tree balanced with SQL hierarchical queries

is there a way I can order this tree in alphabetical order so that the result looks like

LEVEL INDENTED_ENAME
---------- --------------------
1 KING BED
2 BLAKE
3 ALLEN
3 JAMES
MARTIN 3
3 TURNER
WARD 3
2 CLARK
3 MILLER
2 JONES
3 FORD
4 SMITH
3 SCOTT
4 ADAMS

-the original query-

SELECT THE LEVEL
, LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
FROM scott.emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
;

LEVEL INDENTED_ENAME
---------- --------------------
1 KING BED
2 JONES
3 SCOTT
4 ADAMS
3 FORD
4 SMITH
2 BLAKE
3 ALLEN
WARD 3
MARTIN 3
3 TURNER
3 JAMES
2 CLARK
3 MILLER

Hello

Bodin wrote:
Hi Frank, I can order it selectively depending on the level, which means that only siblings stopped at third level, but rest of the brothers and sisters remain Nations United ordered

It's actually quite difficult. You can "ORDER of brothers and SŒURS BY CASE... ', like this:

SELECT  LEVEL
,      LPAD (' ', 3 * LEVEL) || ename     AS indented_ename
FROM      scott.emp
START WITH        mgr     IS NULL
CONNECT BY         mgr      = PRIOR empno
ORDER SIBLINGS BY  CASE
               WHEN  job = 'MANAGER'  THEN  ename
                                          ELSE  NULL
             END
;

In this case to get desired results in table scott.emp, as the lines are LEVEL = 2 if and only if use = "MANAGER".
But if you reference LEVEL in the CASE expression (for example, if you replace ' job = 'MANAGER' ' with "2 LEVEL =" above "), then you will get the error" ORA-00976: LEVEL, PRIOR or ROWNUM not allowed here. "
The best way I can think to do exactly what you asked is to do 2 CONNECT BY queries; one just to get the LEVEL and the other for the brothers and SŒURS ORDER BY:
{code}
WITH got_lvl AS
(
SELECT LEVEL AS lvl
Bishop
empno
ename
FROM scott.emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
)
SELECT lvl
, LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
OF got_lvl
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
BROTHERS AND SŒURS OF ORDER OF CASES
ONCE lvl = 2 THEN ename
ANOTHER NULL
END
;
{code}
Why you can't simply "Brothers and SŒURS of ORDER BY ename" at all levels? If all you care is the order of the items of LEVEL = 2, then this is probably the most effective and simplest way. It really hurt anything if nodes on levels 3, 4, 5,... are in order, too?

Here's something you can do if you want to order by different unique things to different levels:
{code}
WITH got_sort_key AS
(
SELECT LEVEL AS lvl
, LPAD (' ', 3 * LEVEL) | Ename AS indented_ename
empno
SYS_CONNECT_BY_PATH (LPAD (CASE
WHEN LEVEL = 2
THEN ename
Of OTHER TO_CHAR (empno)
END
10
)
, ','
) AS sort_key
FROM scott.emp
START WITH mgr IS NULL
CONNECT BY PRIOR empno = mgr
)
SELECT lvl
indented_ename
empno
OF got_sort_key
ORDER BY sort_key
;
{code}
However, all possible values of the CASE expression must uniquely identify the node; otherwise, the output won't necessarily hierarchical order. You can assign arbitrary unique IDS to the lines (using the ROW_NUMBER analytic function, for example), but that requires another subquery and is also complex and perhaps as ineffective as the solution above with 2 garages CONNECT.

Tags: Database

Similar Questions

  • Building the tree balanced with SQL hierarchical queries

    Hi all

    I have the following hierarchical data with different levels of subtree:

    A0
    -A001
    -A00101
    A1
    -A101
    A2
    -A201
    -A20101
    -A201010001

    A0 subtree has 3 levels, A1 subtree has 2 levels and subtree of the A3 is level 4. I want to generate a tree balanced on the data with all levels of the subtree equal to the maximum number of levels available in the whole tree which, in this particular case, is 4.

    I don't know that it is possible with SQL. Script to generate the above mentioned are as below:

    CREATE TABLE codes_tree
    (node_id VARCHAR2 (10))
    parent_node_id VARCHAR2 (10)
    );
    INSERT INTO codes_tree VALUES ('A0', NULL);
    INSERT INTO codes_tree VALUES ('A001', 'A0');
    INSERT INTO codes_tree VALUES ('A00101', 'A001');
    ---
    INSERT INTO codes_tree VALUES ('A1', NULL);
    INSERT INTO codes_tree VALUES ('A101', 'A1');
    ---
    INSERT INTO codes_tree VALUES ('A2', NULL);
    INSERT INTO codes_tree VALUES ('A201', 'A2');
    INSERT INTO codes_tree VALUES ('A20101', 'A201');
    INSERT INTO codes_tree VALUES ('A201010001', 'A20101');

    Any help will be much appreciated.

    Thank you... Best regards

    Published by: naive2Oracle on May 12, 2011 19:40

    Published by: naive2Oracle on May 12, 2011 19:41

    Hello

    Of course, you can do it in SQL.
    One way is to take the normal output of hierarchical and manipulate the result set so that the leaves are repeated as often as necessary to make all branches of the same length. I have Oracle 10.2 available right now, so here's a solution that will work in Oracle 10 (and more):

    WITH     original_hierarchy     AS
    (
         SELECT     node_id
         ,     LEVEL               AS lvl
         ,     CONNECT_BY_ISLEAF     AS isleaf
         ,     ROWNUM               AS rnum
         FROM     codes_tree
         START WITH     parent_node_id     IS NULL
         CONNECT BY     parent_node_id     = PRIOR node_id
    )
    ,     got_max_lvl     AS
    (
         SELECT     o.*
         ,     MAX (lvl) OVER ()     AS max_lvl
         FROM     original_hierarchy     o
    )
    SELECT       LPAD ( ' '
                , 3 * ( ( d.lvl
                     + NVL (c.rnum, 1)
                     - 1
                     )
                   - 1
                   )
                ) || CASE
                   WHEN c.rnum > 1
                   THEN '*' || d.node_id || '*'
                   ELSE        d.node_id
                  END          AS display_id
    FROM            got_max_lvl     d
    LEFT OUTER JOIN       got_max_lvl     c  ON     d.isleaf     = 1
                           AND     c.rnum          <= 1 + d.max_lvl - d.lvl
    ORDER BY  d.rnum
    ,       c.rnum
    ;
    

    With the help of Oracle 11.2, it would be preferable to generate original_hierarchy as above, but to manipulate using a WITH recursive clause.
    Analytical functions often interfere with CONNECT BY, so I used a separate subquery to get max_lvl, do CONNECT BY in a sub-querry and analytic function in a separate subquery. I don't know what is needed on all versions.

    Output of your sample data:

    DISPLAY_ID
    -------------------------------
    A0
       A001
          A00101
             *A00101*
    A1
       A101
          *A101*
             *A101*
    A2
       A201
          A20101
             A201010001
    

    Below is a generic version of the same query, which I used to test this on scott.emp:

    DEFINE     table_name     = scott.emp
    DEFINE     id_col          = empno
    DEFINE     parent_id_col     = mgr
    DEFINE     display_col     = ename
    
    WITH     original_hierarchy     AS
    (
         SELECT     &display_col          AS display_txt
         ,     LEVEL               AS lvl
         ,     CONNECT_BY_ISLEAF     AS isleaf
         ,     ROWNUM               AS rnum
         FROM     &table_name
         START WITH     &parent_id_col     IS NULL
         CONNECT BY     &parent_id_col     = PRIOR &id_col
    )
    ,     got_max_lvl     AS
    (
         SELECT     o.*
         ,     MAX (lvl) OVER ()     AS max_lvl
         FROM     original_hierarchy     o
    )
    SELECT       LPAD ( ' '
                , 3 * ( ( d.lvl
                     + NVL (c.rnum, 1)
                     - 1
                     )
                   - 1
                   )
                ) || CASE
                   WHEN c.rnum > 1
                   THEN '*' || d.display_txt || '*'
                   ELSE        d.display_txt
                  END          AS display_id
    FROM            got_max_lvl     d
    LEFT OUTER JOIN       got_max_lvl     c  ON     d.isleaf     = 1
                           AND     c.rnum          <= 1 + d.max_lvl - d.lvl
    ORDER BY  d.rnum
    ,       c.rnum
    ;
    

    Output:

    DISPLAY_ID
    -----------------------------
    KING
       JONES
          SCOTT
             ADAMS
          FORD
             SMITH
       BLAKE
          ALLEN
             *ALLEN*
          WARD
             *WARD*
          MARTIN
             *MARTIN*
          TURNER
             *TURNER*
          JAMES
             *JAMES*
       CLARK
          MILLER
             *MILLER*
    

    Published by: Frank Kulash, May 13, 2011 06:38
    Adding the generic version

  • How to establish links of Labview with SQL server database Toolkit

    I'm a database newbie, but I have to use MS SQL server (2008) to store my data. I am well equipped with all the features of Labview, don't know how to use it properly. I now complete development, including the toolbox database. My latest version of labview is 8.6.1. Side material, I have cFP2220 and many modules of differnet kind.

    Here is a useful link that I found on the web:

    1. I got the database creation procedure (pdf file) to link the udl.

    http://decibel.NI.com/content/docs/doc-4602

    It gives a step-by-step login procedure to MS Access, and I'm able to save data to MS Access with the database Toolbox. However, I could not understand how to establish a chain of connection or udl to SQL server. In other words, I hope someone can explain in detail what is the procedure to set up such a link.

    2. I learned about the forum that there is a LabSQL, but it takes some knowledge of SQL statement. I would walk away from him, as I am not familiar with SQL.

    3. the VI I used for the recording of data in DB are very similar to "Create database Table.vi" found in the sample.

    In short, I think that I just need someone who has experience with the connection to the server SQL with Labview to show me the steps to link to SQL.

    Thank you very much

    You may not create a database in SQL Server using the control panel ODBC or a UDL. You must create a database by using SQL Server tools. (In fact, you can use SQL statements to create a database, which is what's really going on by using SQL Server tools. However, I don't know if the database Toolbox has the screws required to send these types of SQL statements.). Once you have created the database you can create tables using SQL Server tools, or you can use the screw of toolbox database.

    You try to run SQL Server on your computer? SQL Server is usually running on a server. You try to use SQL Server Express?

    Assuming that you have SQL Server running and a database has been created, then here are the steps needed to create a UDL to connect:

    1. In Windows Explorer, create a text file and rename the text file so that there a .udl extension (like this PDF).
    2. Double-click the UDL file.
    3. Change to the tab 'supplier '.
    4. Select 'Microsoft OLE DB for SQL Server provider'.
    5. Click on the ' next > ' button. It changes you to the tab 'connection '.
    6. In the drop-down menu, select your SQL Server. If it is not listed, try clicking on the Refresh"" button. If this does not meet the list, then you will need to enter manually.
    7. In the section "#2" specify the authentication method and credentials, if necessary, to connect to SQL Server.
    8. In the section "#3" specify the database that will be used, which is the one that you created earlier using the SQL Server tools. NOT SELECT THE MASTER DATABASE. If you do, you will completely screw up your installation of SQL Server.
    9. Click "Test connection" to verify that you can connect to SQL Server.
  • How to order a tree with the help of another column?

    I want to order the nodes of the tree using the column POSITION.

    How can I do this?

    I tried to ORDER BY position in the tree of query design, but who gives a completely weird result for the hierarchy tree.


    http://www.freeimagehosting.NET/uploads/7460540c52.gif

    use the order siblings by clause in your query

     order siblings by position_no
    

    Baig,
    http://baigsorcl.blogspot.com

  • How to extract several Max (amount) with sql

    Hello

    I have this problem,

    I hace this table

    DISPLAY_NAME, MSISDN TRANSACTIONS

    ------------------------- ------------------- ------------

    CM, SA - MERCHANT I 829882904 75

    CM, SA - MERCHANT I 827102931 43

    CM, SA - MERCHANT I 17 824034968

    CM, SA - II MERCHANT 827102931 48

    4 selected lines.

    And I need to get the records corresponding to the highest trasactions by DISPLAY_NAME

    The must Resulet be something like

    DISPLAY_NAME, MSISDN TRANSACTIONS

    ------------------------- ------------------- ------------

    CM, SA - MERCHANT I 829882904 75

    CM, SA - II MERCHANT 827102931 48

    Any ideas?

    TXS so you can help

    Hello

    One way is a Request of Top - N , like this

    WITH got_r_num AS

    (

    SELECT x *- or list columns you want

    Rank () OVER (PARTITION BY display_name

    Operations ORDER BY DESC

    ) AS r_num

    FROM table_x

    -WHERE... - If you need any filtering, put it here

    )

    SELECT *- or the list of all columns except r_num

    OF got_r_num

    WHERE r_num = 1

    ;

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements)
    Point where the above query is to produce erroneous results, and explain, using specific examples, how you get the right results in these places.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).

    See the FAQ forum: https://forums.oracle.com/message/9362002#9362002

  • How to order a N5230A Agilent with LabView, via LAN?

    I want to order a N5230A Agilent via LAN, but I think I have some problems with the VISA of the device configuration or configurations on the device.

    I was looking on the forums, but has not found the solution to my problem. Could someone help me?

    Thank you very much

    I found the solution to my problem.

    The connection to the PNA is authorized with a TCP Socket on port default 5025. In MAX, the IP address and port number need to set to be able to control via LabView PDA.

  • variable with sql reuse various clauses

    Hello

    Is it possible to reuse the same variable with sql different queries in the packages...

    Example:

    I have a Word to say variable

    name of the variable 1): filename

    (2) in variable query: select 'emp.txt' of the double

    so using the name of this variable in the data store, I'm passing filename dynamically, but I need to change the file name to dept.txt emp.txt missing emp.txt food.

    A solution on my side uses a table dump with the file name. more without the use of db tables

    Please share views

    See you soon,.
    Surya

    You will then need the help of beanshell java technology. Variable2 take the second query in cooling mode. Now, create a procedure. At the 1st step of technology will be java beanshell with below codes.

    <>
    String xtr = "#variable2";
    @>

    Now in ko-> step use variable1 in assign mode

    Variable1 =<@=xtr@>

    It will certainly work.

    Thank you.

  • How can I cerate a table with a set of numbers saying 1 to 12 random order but no recurrence.

    How can I cerate a table with a set of numbers saying 1 to 12 random order but no recurrence.

    I know it should be easy, but my brain doesn't work right now


  • How to find assets to a project of the BCC with SQL

    Hello.

    I would like to know how to find assets to a project of the BCC with SQL.

    Thank you.

    Hello.

    You can try this.


    select * from dcs_product where workspace_id in ( Select avm_devline id where the name of (select Workspace for epub_project where display_name = "${name_of_project}"));

    For each version of an asset is recorded the id workspace on the workspace_idfield. This workspace is related to the project in the field name and the workspace field in table epub_projecttable avm_devline .


    But this query must be performed from the active table. Example: Product = dcs_product, sku = dcs_sku, class = dcs_category and so on.

    Thank you rtreto for the help.

  • How do I get the data of "Regulatory BOM" Formulation with SQL query output

    Hello

    We would like to implement a State of BiPublisher that displays "Regulation BOM" (wording-> click on TAB Formulation on exit Popup-> TAB Composition) information table.

    How could get us this information with an SQL query?

    Thank you

    Annarosa

    Hi, given 'Regulatory BOM' output of the Formulation are more complicated than expected. Attached is an example. You can test and make the appropriate changes to your report.

  • How to connect to microsoft sql server with sql developer 4.1 2014

    Hello

    Please,

    I need to connect to a Microsoft SQL Server 2014 with SQL Developer 4.1 database, I installed the appropriate jdbc driver microsoft as having the active tab for SQL Server and to add the connection.

    Thank you very much

    We support no migration of SQL Server 2014, but you should be able to connect. There is a problem around tables in the connection of the navigation tree, but you should be able to execute queries and PROBABLY get a migration project going.

  • How to execute a stored procedure on Sybase with SQL Developer

    We have accessed Sybase 15 with SQL developer.

    We can see the data in the table, if we do not, run the stored procedure (for instance sp_who) developed on Sybase.

    Could you tell me how we execute the stored procedure on Sybase with SQL Developer Sybase?

    Thank you

    Shige

    We will not intended to be a Sybase ASE customer.

    But

    A SQL Developer... @dermotoneill: Workheet advice

  • How to connect my APEX with SQL Developer workspace?

    Hi all

    I am a new user of Oracle Apex. Is there a way to connect to my workspace created to http://apex.oracle.com/pls/apex with SQL Developer. If so, then let me know how. If someone has done successfully then please help me.

    Thank you

    Gerard

    Hi Gerard,

    It is not possible to do this on apex.oracle.com.

    Joel

  • How to create multiple tables with SQL commands

    Hi, first of all, is it possible to create a table and then one more both with SQL commands?
    because I tried to do this in the following way
    Example:
    CREATE TABLE 'HB_Product')
    "productId" number 4 NOT NULL.
    "productName" VARCHAR2 (20) NOT NULL,
    "prodPricePerTon" NUMBER (10,2).
    "HB_Product_PK" PRIMARY KEY CONSTRAINT ("productId")
    )
    /
    CREATE TABLE 'HB_Operations')
    "orderNo" NUMBER (5) NOT NULL,
    'lineNo' number 4 NOT NULL.
    "billNo" NUMBER (10) NOT NULL,
    'actions' VARCHAR2 (15).
    'place' VARCHAR2 (15).
    "actDate" DATE NOT NULL,
    "totWeight" NUMBER (6.3).
    'HB_Operations_PK' CONSTRAINT PRIMARY KEY ('lineNo')
    )
    /

    I copied some of the syntax for creating the table object browser, but I preffer to use my own sql.
    It gives me an error "Missing or option not valid."

    Can someone explain to me how to do it properly, or why it is not possible?

    Best regards from Stan!

    862377 wrote:
    so you're saying I can't do several tables at the same time?

    Yes... Well,... not this way

    You can do this way

    create schema authorization alex
    CREATE TABLE "HB_Product" (
    "productId"    NUMBER(4) NOT NULL,
    "productName"    VARCHAR2(20) NOT NULL,
    "prodPricePerTon"    NUMBER(10,2),
    CONSTRAINT "HB_Product_PK" PRIMARY KEY ("productId")
    )
    CREATE TABLE "HB_Operations" (
    "orderNo"    NUMBER(5) NOT NULL,
    "lineNo"    NUMBER(4) NOT NULL,
    "billNo"    NUMBER(10) NOT NULL,
    "actions"    VARCHAR2(15),
    "place"    VARCHAR2(15),
    "actDate"    DATE NOT NULL,
    "totWeight"    NUMBER(6,3),
    CONSTRAINT "HB_Operations_PK" PRIMARY KEY ("lineNo")
    )
    /
    

    The question is: why do you want to create "at the same time? What is the harm in creating one after the other?

    some tips (maybe not desired):
    do not use quotation marks in your statement, this will create column names and the table out.

  • SQL query: How to match multiple names strictly with its appropriate values

    Hi all

    Assume there is a table of CODES (with 3 columns) as follows:...
    ------------------------------------------------
    Name ID value
    ------------------------------------------------
    SFO 100 080
    200 NY 044
    300. THE 040
    ------------------------------------------------

    I would need to write a SQL to retrieve the rows that match few of names and values. For example: (1) name = "NY" and value = '044' and (2) name = "LA" and value = "040".

    I wrote this sql...
    SELECT id, name, value of CODES whose name IN ('NY', THE ') and the value IN ('044 ', ' 040')
    This returns 2 rows as expected.

    At the same time, even for the following query, the same 2 rows are returned (which is false)
    SELECT id, name, value of CODES whose name in ('NY', THE ') and value in ('044 ', ' 444')
    -See the code std 444.

    My requirement is that the above query should return to the line for NY.

    My question is: how to match multiple names strictly with its appropriate values... ? That is to say, unless '040' is specified in the part 'value', the corresponding line in 'LA' should not be returned...

    I feel, nor the case AND neither the case of GOLD can be used in Where clause to check these 4 values.

    Any ideas... ? Can you please let me know... ?

    Thank you
    REDA

    as:

    select id, name, value from CODES where (name, value) in (('NY', '044'), ('LA', '040'))
    

    Published by: Lacotte Renaud on February 16, 2010 10:35

Maybe you are looking for

  • Firefox crashes instantly on the opening.

    Hello I installed "CUSTOM ROM OS" on my Samsung Galaxy Tab 2 (GT-P3100) - Android 5.0.2 "slimrom."Whenever I open the browser, after a few seconds it crashes instantly. This same problem occurs with both the browser. THE OFFICIAL LANGUAGES OF FIRFOX

  • How to remove stains in the base of Windows 2008 Server.

    Hello How to remove stains in base of Windows Server 2008. I'm trying with extend your order but could not understand what would be patch name. Thank you

  • Runtime error! R6002 - floating point not loaded support

    I use a Hardrive external Transcend to back up my computer, but when I just tried to use the backup software of Transcend I get a runtime error that the decimal point floating support is not loadedHow can I fix it?

  • Mislabelling of Media Player music albums

    My Windows Media is strange. I changed the label to some of my music albums, but he has changed the labels of other albums as well. Tried I delete albums concerned the library and tried to reconstruct these albums 'Add to library' of my music from th

  • Windows Live and MSN Premium keep time

    I have Vista and the past few days my Windows Live email continued delay in the middle of the use of the program.  My MSN premium account no longer opens my email and recently stopped because he says that he does not.  There is nothing wrong with my