CTE for Count the Binary Tree nodes

i have the table structure like this :
Create table #table(advId int identity(1,1),name nvarchar(100),Mode nvarchar(5),ReferId int )
insert into #table(name,Mode,ReferId)values('King','L',0)
insert into #table(name,Mode,ReferId)values('Fisher','L',1)
insert into #table(name,Mode,ReferId)values('Manasa','R',1)
insert into #table(name,Mode,ReferId)values('Deekshit','L',2)
insert into #table(name,Mode,ReferId)values('Sujai','R',2)
insert into #table(name,Mode,ReferId)values('Fedric','L',3)
insert into #table(name,Mode,ReferId)values('Bruce','R',3)
insert into #table(name,Mode,ReferId)values('paul','L',4)
insert into #table(name,Mode,ReferId)values('walker','R',4)
insert into #table(name,Mode,ReferId)values('Diesel','L',5)
insert into #table(name,Mode,ReferId)values('Jas','R',5)
insert into #table(name,Mode,ReferId)values('Edward','L',6)
insert into #table(name,Mode,ReferId)values('Lara','R',6)
select *from #table
How do i write the CTE for count the Binary tree nodes on level basis. Here is the example,
now,what i want to do is if i'm going to calculate the Count of the downline nodes.which means i want to calculate for '1' so the resultset which i'm expecting
count level mode
1 1 L
1 1 R
2 2 L
2 2 R
4 3 L
2 3 R
How do i acheive this,i have tried this
with cte (advId,ReferId,mode,Level)
select advId,ReferId,mode,0 as Level from #table where advid=1
union all
select a.advId,a.ReferId,a.mode ,Level+1 from #table as a inner join cte as b on b.advId=a.referId
select *From cte order by Level
i hope its clear. Thank you

See Itzik Ben-Gan examples for the subject
  empid   int         NOT NULL,
  mgrid   int         NULL,
  empname varchar(25) NOT NULL,
  salary  money       NOT NULL,
  CONSTRAINT FK_Employees_mgrid_empid
    FOREIGN KEY(mgrid)
    REFERENCES Employees(empid)
CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
INSERT INTO Employees VALUES(1 , NULL, 'Nancy'   , $10000.00)
INSERT INTO Employees VALUES(2 , 1   , 'Andrew'  , $5000.00)
INSERT INTO Employees VALUES(3 , 1   , 'Janet'   , $5000.00)
INSERT INTO Employees VALUES(4 , 1   , 'Margaret', $5000.00) 
INSERT INTO Employees VALUES(5 , 2   , 'Steven'  , $2500.00)
INSERT INTO Employees VALUES(6 , 2   , 'Michael' , $2500.00)
INSERT INTO Employees VALUES(7 , 3   , 'Robert'  , $2500.00)
INSERT INTO Employees VALUES(8 , 3   , 'Laura'   , $2500.00)
INSERT INTO Employees VALUES(9 , 3   , 'Ann'     , $2500.00)
INSERT INTO Employees VALUES(10, 4   , 'Ina'     , $2500.00)
INSERT INTO Employees VALUES(11, 7   , 'David'   , $2000.00)
INSERT INTO Employees VALUES(12, 7   , 'Ron'     , $2000.00)
INSERT INTO Employees VALUES(13, 7   , 'Dan'     , $2000.00)
INSERT INTO Employees VALUES(14, 11  , 'James'   , $1500.00)
The first request is probably the most common one:
 returning an employee (for example, Robert whose empid=7) 
and his/her subordinates in all levels. 
The following CTE provides a solution to this request:
WITH EmpCTE(empid, empname, mgrid, lvl)
  -- Anchor Member (AM)
  SELECT empid, empname, mgrid, 0
  FROM Employees
  WHERE empid = 7
  -- Recursive Member (RM)
  SELECT E.empid, E.empname, E.mgrid, M.lvl+1
  FROM Employees AS E
      ON E.mgrid = M.empid
Using this level counter you can limit the number of iterations
 in the recursion. For example, the following CTE is used to return 
all employees who are two levels below Janet:
WITH EmpCTEJanet(empid, empname, mgrid, lvl)
  SELECT empid, empname, mgrid, 0
  FROM Employees
  WHERE empid = 3
  SELECT E.empid, E.empname, E.mgrid, M.lvl+1
  FROM Employees as E
    JOIN EmpCTEJanet as M
      ON E.mgrid = M.empid
  WHERE lvl < 2
SELECT empid, empname
WHERE lvl = 2
As mentioned earlier, CTEs can refer to
 local variables that are defined within the same batch.
 For example, to make the query more generic, you can use 
variables instead of constants for employee ID and level:
DECLARE @empid AS INT, @lvl AS INT
SET @empid = 3 -- Janet
SET @lvl   = 2 -- two levels
WITH EmpCTE(empid, empname, mgrid, lvl)
  SELECT empid, empname, mgrid, 0
  FROM Employees
  WHERE empid = @empid
  SELECT E.empid, E.empname, E.mgrid, M.lvl+1
  FROM Employees as E
    JOIN EmpCTE as M
      ON E.mgrid = M.empid
  WHERE lvl < @lvl
SELECT empid, empname
WHERE lvl = @lvl
Results generated thus far might be returned (but are not guaranteed to be), 
and error 530 is generated. You might think of using the MAXRECURSION option 
to implement the request to return employees who are two levels below 
Janet using the MAXRECURSION hint instead of the filter in the recursive member
WITH EmpCTE(empid, empname, mgrid, lvl)
  SELECT empid, empname, mgrid, 0
  FROM Employees
  WHERE empid = 1
  SELECT E.empid, E.empname, E.mgrid, M.lvl+1
  FROM Employees as E
    JOIN EmpCTE as M
      ON E.mgrid = M.empid
WITH EmpCTE(empid, empname, mgrid, lvl, sortcol)
  SELECT empid, empname, mgrid, 0,
    CAST(empid AS VARBINARY(900))
  FROM Employees
  WHERE empid = 1
  SELECT E.empid, E.empname, E.mgrid, M.lvl+1,
    CAST(sortcol + CAST(E.empid AS BINARY(4)) AS VARBINARY(900))
  FROM Employees AS E
      ON E.mgrid = M.empid
  REPLICATE(' | ', lvl)
    + '(' + (CAST(empid AS VARCHAR(10))) + ') '
    + empname AS empname
ORDER BY sortcol
(1) Nancy
 | (2) Andrew
 |  | (5) Steven
 |  | (6) Michael
 | (3) Janet
 |  | (7) Robert
 |  |  | (11) David
 |  |  |  | (14) James
 |  |  | (12) Ron
 |  |  | (13) Dan
 |  | (8) Laura
 |  | (9) Ann
 | (4) Margaret
 |  | (10) Ina
Best Regards,Uri Dimant SQL Server MVP,
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence

Similar Messages

  • Queue for Binary Tree Node

    I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
    public class BTNode {
         private customer     item;
         private BTNode     left;
         private BTNode     right;
         public BTNode() {// constructor
              item = null;
              left = right = null;
         public BTNode(customer newItem) {// constructor
              item = newItem.clone();
              left = right = null;
         public void setItem(customer newItem) {// set methods
              item = newItem.clone();
         public void setLeft(BTNode newLeft) {
              left = newLeft;
         public void setRight(BTNode newRight) {
              right = newRight;
         public customer getItem() {     // get methods
              return item;
         public BTNode getLeft() {
              return left;
         public BTNode getRight() {
              return right;
    public class Queue1 extends BTNode {
        public Queue1() {
        public void enqueue(BTNode newItem) {
        public void dequeue() {

    public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
    You probably want to aggregate a List.

  • Searching for a certain  binary tree from another tree........

    I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
    Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
    Tree B has a similar structure.
    The node used for both A and B.
    Node left;
    Node right;
    My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
    So, the method should look like:
    public Node search(Node rootOfA, Node rootOfB){
    I know a simple recursive fuction can do the job. The question is all about the effciency....
    I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
    Anyone knows of that? Any friend can give a sound solution?
    Thank you all in advance.
    Message was edited by:

    I'm not too sure if this would help but there goes.
    I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
    Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.

  • Af:tree - how do I highlight the selected tree node?

    I checked the generated CSS file. I found that when a tree node is selected, the related CSS attribute is:
    I created a customized CSS attribute, but then all of the links have the customized CSS attributes.
    How do I just highlight the selected tree node link?

    try doing the onclick javascript method
    you have to place it on the node element and id must be made dynamic
    for this use 'this.id'
    by which the current id of the node is passed
    and by capturing the id name in a var
    use the same for invoking its selected property and make it true
    like this
    var currentid = this.id;
    this.form.currentid.selected = true;

  • Highlight the selected Tree Node

    Hello Everyone,
    Can someone plz tell me how to highlight the selected tree node ?
    After selection, user should be able to see which node was last selected.

    for me it is not really clear what you have done. Sorry!
    Because I have problems to paste code, I will describe how you can test that function.
    Take the BSP application HTMLB_SAMPLES and copy it to ZHTMLB_SAMPLES. Take page "treeviewSample.htm" and add the following node behind node22:
    <htmlb:treeNode id   = "node23"
                      text = "Node 2.2, normal text"
    Perhaps this will show you how it works and help you.
    As far as I can see the attribute "selection" can't be set via table.
    Best regads
    Edited by: Renald Wittwer on Jan 21, 2010 1:36 PM

  • How to alter the alv tree node text?

      i want to alter the alv tree node text, many people say it cann't be changed, but
    i look into the sample code 'BCALV_TREE_04', the average funtion(select a column and then select average function in the tool bar) can alter the tree node text dynamically.
      i try to look into the source code, the it's the sap standard code, all the funtions that user input, it goes to the statement "  CALL METHOD cl_gui_cfw=>dispatch.", and i don't understand what this statement do, can someone helps me?

    The ALV tree report produces uses OBJECT METHOD functionality in-order to produce a
    tree structured ALV output. 
    The creation of an ALVtree report first requires the creation of a simple program to build the ALV
    details such as the fieldcatalog and to call a screen which will be used to display the ALVTree.
    The screen should be created with a 'custom control' where you wish the ALVtree report to appear.
    For the following example it will have the name 'SCREEN_CONTAINER'.
    reward point if helpful.

  • Program (PL/SQL) for count the registers of all tables in a schema

    I create a little program , for count the registers of all tables in the schema...
    If you need , send me your email...

    You can create a script by yourself by executing the script mentioned below:
    Connect as sys or system....
    SQL> spool test.sql
    SQL> select 'select count(*) from '||owner||'.'||table_name||';' from dba_tables;
    SQL> spool off;
    Hope this helps.

  • Reports for Count the number of External Candidate Registration - ERecruitment

    Dear Experts
    Anyone know a reports for Count the number of External Candidate Registration - ERecruitment?

    http://scn.sap.com/thread/784769 http://scn.sap.com/thread/1625606 read here!

  • How can I edit the selected tree node immediately?

    I have completed a popup menu ,which appeares when I have a mouse rightclicked event
    over the selected tree node.when I selected the popup menu item,i can edit the tree node ,but
    I feel that the tree celleditor appear slowly ,what should i do? the following is my code:
    menuItemRenameNode.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    void renameNode_ActionPerformed(ActionEvent ae){
    this.getCellEditor().addCellEditorListener(new CellEditorListener(){
    public void editingCanceled(ChangeEvent e){
    CellEditor cellEditor =(CellEditor)e.getSource();
    System.out.println("editing canceled:"+cellEditor.getCellEditorValue().toString());
    protected boolean canEditImmediately(EventObject e){
    return true;
    public void editingStopped(ChangeEvent e){
    CellEditor cellEditor =(CellEditor)e.getSource();
    System.out.println("editing stopped:"+cellEditor.getCellEditorValue().toString());

    Please check the suggestions in the thread: https://forums.adobe.com/thread/692020?tstart=0
    | T. Ravi Kumar

  • When the device tree node(dev_info_t) is built for a pseudo device?

    Hi Expert,
    I am a new driver writer. I am writing a pseudo driver.
    As my understanding, the a device node (dev_info_t) must exist before the attach routine is called.
    int attach(dev_info_t *dip, ddi_attach_cmd_t cmd);
    For the hardware device, the node will be built when the system boots.
    But when the node is built on the device tree for the pseudo device.

    Two options:
    - Use another payment method like redeeming and iTunes gift card.
    - Create a new account that is only good for app by using the instructions here:
    Creating an iTunes Store, App Store, iBookstore, and Mac App Store account without a credit card
    Please follow the instructions. oyu have to do it exactly as it says.

  • Retieve the related childern to the selected Tree Node

    Hello all,
    From here i got the folowing code,it helps me to retrieve the whole record which is related to the selected node in
         rank   number := 0;
         rank :=
             :system.trigger_node, ftree.node_depth);
              if rank >= 1  then
                       GO_BLOCK ('INSP_EQUIPMENT_TYPE');
                      set_block_property ('INSP_EQUIPMENT_TYPE', default_where, 
                               :system.trigger_node, ftree.node_value)); 
              end if;
              end; What i want to do is to retieve not only the current record for the selected node but aslo the related childern in the tree to this node.
    Could anyboady help me pls. ?!

    Hi Tony,
    what i am trying to do is to display all childern related to the parent 's node selected from the tree that's works fine..
    But i want to display the related datablock selected to the child itself the following can't do that can u help me doing it pls...!
         rank number := 0;
         HTREE$ ITEM := Find_Item('TREE_BLOCK_TEST.TREE13');
         rank :=     ftree.get_tree_node_property
         ('TREE_BLOCK_TEST.TREE13',:system.trigger_node, ftree.node_depth);
         if rank = 1 then
         set_block_property ('INSP_EQUIPMENT_TYPE', default_where
              , 'parent_id='||ftree.get_tree_node_property('TREE_BLOCK_TEST.TREE13',
              :system.trigger_node, ftree.node_value));
                        GO_BLOCK ('INSP_EQUIPMENT_TYPE');
         elsif rank > 1 then
              set_block_property ('INSP_EQUIPMENT_TYPE', default_where
              :system.trigger_node, ftree.node_value));
         END IF;
         END IF;

  • How can I get the adf-tree-node's attributes?

    I want get the attributes in the method of "selectionListener"?
    How can I do?
    I only know :
    RichTree treeId;
    RowKeySet keySet = treeId.getSelectedRowKeys();

    You don't want to maintain a reference to the last selected node, but to the last selected path. Nodes within a tree are addressed using a TreePath, with contains references to each node from the root, down to a specific node. Look at the JavaDocs of javax.swing.tree.TreePath for more info.
    Also, JTree has getter/setter methods for the selectionPath.

  • How to set the default tree node in JTree?

    I want to set a default tree node in JTree when start the program,
    what is the method or the function to call?

    If you by "default" mean "selected", then you can use one of the setSelectionXXX methods in the JTree API.
    If you by "default" mean something else, never mind this post :-)

  • Scheduling does not take the factory calendar for counting the workdays

    I am scheduling my jobs in CPS 8 and I have imported my Factory calenders also. When using Factory calendars for scheduling the jobs for the 6th working day of every month, Its does not count the Saturday as a working day, where as the calendar I am using has Working day on Saturday.
    Why is it so? And is there a way to solve this ?
    Please suggest. Any help is appreciated.

    Hi All,
    I have used this same logic for scheduling jobs scheduling for the nth work days of every month.
    But I have a job, where it is required to be scheduled on the 5th workday of a month and it is submitted once in every 6 months.
    When I schedule it for every month, it works fine. But when I use a submit frame to submit it for once in every 6 months, it does not work.
    Can anyone suggest how to do it ? I used a embedded window to check it also, which didn't work.

  • Report for counting the number of interfaces in each device

    Hi, we have LMS 4.0.1 and we would like to know how many gigabitEthernet interfaces and how many fastEthernet interfaces does each device have. If we create a custom report template with the conditions "Interface:Type:Contains:Gi" OR "Interface:Type:Contains:Fa" we get the interfaces that match the criteria but we also need the count, and this is what we don't know how to do it.
    Does anyone know how can we do it?

    Suppress results rows for number of items..that is 10,20...
    Calculate result rows only for sales order ...1000000...
    You should get intended result with this settings
    N Ganesh

Maybe you are looking for