473,785 Members | 2,794 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to query this table into the result like this?

per

im not very good at sql but need to query the database to use in my
programming script.
if the database is just like this

id name parent_id
1 A null <----- root
2 B 1
3 C 1
4 D 1
5 E 2
6 F 2
7 G 3
8 H 4
9 I 4
10 J 4
11 K 9

the data in the above table is just like some sort of tree data
which have parent and child node
and now,how to query into the result like this

the deepest node is in level 4

what i want is how deep this tree data is?
anyone show me the query script or store procedure to find the
result please?
many thanks in advance,

--
Posted via http://dbforums.com
Jul 20 '05 #1
1 3666
"per" <me*********@db forums.com> wrote in message news:31******** ********@dbforu ms.com...

im not very good at sql but need to query the database to use in my
programming script.
if the database is just like this

id name parent_id
1 A null <----- root
2 B 1
3 C 1
4 D 1
5 E 2
6 F 2
7 G 3
8 H 4
9 I 4
10 J 4
11 K 9

the data in the above table is just like some sort of tree data
which have parent and child node
and now,how to query into the result like this

the deepest node is in level 4

what i want is how deep this tree data is?
anyone show me the query script or store procedure to find the
result please?
many thanks in advance,

--
Posted via http://dbforums.com


CREATE TABLE Tree
(
node_id INT NOT NULL PRIMARY KEY,
node_name VARCHAR(10) NOT NULL UNIQUE,
parent_id INT NULL REFERENCES Tree (node_id)
)

-- Sample data
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (1, 'A', NULL)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (2, 'B', 1)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (3, 'C', 1)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (4, 'D', 1)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (5, 'E', 2)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (6, 'F', 2)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (7, 'G', 3)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (8, 'H', 4)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (9, 'I', 4)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (10, 'J', 4)
INSERT INTO Tree (node_id, node_name, parent_id)
VALUES (11, 'K', 9)

-- Returns a table of all descendants of a given node and their level numbers
-- If the given node is NULL, use root node of tree
CREATE FUNCTION Descendants(@ro ot_node VARCHAR(10) = NULL)
RETURNS @nodes TABLE
(node_id INT NOT NULL PRIMARY KEY,
level_number INT NOT NULL CHECK (level_number >= 0))
AS
BEGIN
IF @root_node IS NULL
SELECT @root_node = node_name
FROM Tree
WHERE parent_id IS NULL
IF NOT EXISTS (SELECT * FROM Tree WHERE node_name = @root_node)
RETURN
DECLARE @level_number INT,
@next_level_num ber INT
SELECT @level_number = 0,
@next_level_num ber = 1
INSERT INTO @nodes (node_id, level_number)
SELECT node_id, @level_number
FROM Tree
WHERE node_name = @root_node
WHILE EXISTS (SELECT * FROM @nodes
WHERE level_number = @level_number)
BEGIN
INSERT INTO @nodes (node_id, level_number)
SELECT T.node_id, @next_level_num ber
FROM @nodes AS N
INNER JOIN
Tree AS T
ON N.level_number = @level_number AND
N.node_id = T.parent_id
SELECT @level_number = @next_level_num ber,
@next_level_num ber = @next_level_num ber + 1
END
RETURN
END

CREATE VIEW TreeDepth (depth)
AS
SELECT COALESCE(MAX(le vel_number) + 1, 0)
FROM Descendants(DEF AULT)

SELECT depth
FROM TreeDepth

depth
4

To find the depth of the tree rooted at other than the tree's root node,
e.g., the depth of the tree rooted at node C, one can do the following

SELECT COALESCE(MAX(le vel_number) + 1, 0) AS depth
FROM Descendants('C' )

depth
2

Regards,
jag
Jul 20 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
8565
by: Felix | last post by:
Hi, I've a problem: I want to have the result of my Mysql Query in a Table in my php file. Now I've this: <?
13
2735
by: Wescotte | last post by:
Here is a small sample program I wrote in PHP (running off Apache 1.3.31 w/ PHP 5.0.1) to help illustrates problem I'm having. The data base is using DB2 V5R3M0. The client is WinXP machine using the iSeries Client Access Driver ver 10.00.04.00 to connect to the database. The problem is that executing the exact same SQL select statement more than twice int a row stops produces results. The first two instances will always produce the...
3
1955
by: Nick Truscott | last post by:
<? // scoreinput.php - input a match score when match selected from list ?> <html> <head> <basefont face="Verdana"> </head> <body>
2
8542
by: Mike Leahy | last post by:
Hello all, This question is related to updating tables - is there any way to calculate or update the values in a column in a table to the values in a field produced by a query result? An example of what I'm trying to do is below: update (tbl_ind_mananas LEFT JOIN (select count(*) as count, (dubicacion || zona || manzana) as cod_manzana from tbl_censo_poblacion_1993 group by dubicacion, zona, manzana) tbl1 on relacion = cod_manzana) as...
2
293
by: Maxi | last post by:
I have 101 fields (Field name P1, P2 .... P100 and Result) P1 to P100 has random numbers from 1 to 10. I want to run a query to update the 101st field (Result). It should check the entire record 1 and find out count where the number is greater than or equal to 6 and update the result field accordingly. Eg. P1 P2 P3 P4 P5 Result
7
3391
by: serge | last post by:
How can I run a single SP by asking multiple sales question either by using the logical operator AND for all the questions; or using the logical operator OR for all the questions. So it's always either AND or OR but never mixed together. We can use Northwind database for my question, it is very similar to the structure of the problem on the database I am working on. IF(SELECT OBJECT_ID('REPORT')) IS NOT NULL DROP TABLE REPORT_SELECTION
3
1966
by: cover | last post by:
I have a table with 50 fields that receive input depending on whether that input came in from a 'shaker' form or a 'conveyor' form. Input from the 'conveyor' form might populate 25 fields while input from the 'shaker' form will populate another 20-25 fields but not the same fields (however there are about 10 common fields to both). I'd thought about using two tables (one for 'conveyor' and the other for 'shaker') but thought I'd try just...
4
1997
by: frizzle | last post by:
Hi there, Still building my forum. I have a certain mysql-query i just can't figure out. These are my tables (simplified): categories -> id, description forums -> id, cat_id, description threads -> id, forum_id, date, title, text I suppose each speaks for itself.
24
19915
by: clare at snyder.on.ca | last post by:
I have a SQL query I need to design to select name and email addresses for policies that are due and not renewed in a given time period. The problem is, the database keeps the information for every renewal in the history of the policyholder. The information is in 2 tables, policy and customer, which share the custid data. The polno changes with every renewal Renewals in 2004 would be D, 2005 S, and 2006 L. polexpdates for a given customer...
11
16333
by: funky | last post by:
hello, I've got a big problem ad i'm not able to resolve it. We have a server running oracle 10g version 10.1.0. We usually use access as front end and connect database tables for data extraction. We have been using oracle client 10.1.0.2 with it's odbc for a while without problem. The problem arose when we decided to reconnect all the tables and save password. Some query became suddenly very slow. Then I've discovered that the tables...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10329
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10152
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10092
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.