sql 图 ,树,层次
Posted 郎喜集团
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 图 ,树,层次相关的知识,希望对你有一定的参考价值。
UDF:用户定义函数
CTE:通用 表 表达式
set nocount on;
use zhubenxi
go
if object_id(‘dbo.Parts‘) is not null
drop table dbo.Parts;
if OBJECT_ID (‘dbo.BOM‘) IS NOT NULL
DROP TABLE DBO.BOM;
create table dbo.Parts
(
partid int not null primary key,
partname varchar(25) not null
);
insert into dbo.Parts (partid ,partname ) values(1,‘Black tea‘),(2,‘white tea‘),(3,‘latte‘),(4,‘espresso‘),(5,‘double espresso‘),(6,‘cup cover‘),(7,‘regular cup‘),(8,‘stirrer‘),(9,‘espresso cup‘),(10,‘tea shot‘),(11,‘milk‘),(12,‘coffe shot‘),(13,‘tea leaves‘),(14,‘water‘),(15,‘sugar bag‘),(16,‘ground coffee‘),(17,‘coffee beans‘)
create table dbo.BOM
(
partid int not null references dbo.Parts,
assemblyid int null references dbo.Parts,
unit varchar(3) not null ,
qty decimal(8,2) not null,
unique(partid,assemblyid),
check(partid<> assemblyid)
)
insert into dbo.BOM (partid ,assemblyid ,unit ,qty ) values(1,null,‘EA‘,1.00),(2,null,‘EA‘,1.00),(3,null,‘EA‘,1.00),(4,null,‘EA‘,1.00),(5,null,‘EA‘,1.00),(6,1,‘EA‘,1.00),(7,1,‘EA‘,1.00),(10,2,‘EA‘,1.00),(11,15,‘EA‘,1.00),(12,3,‘EA‘,1.00),(13,4,‘EA‘,1.00),(14,2,‘ML‘,205.00),(15,7,‘EA‘,13.00),(16,12,‘G‘,15.00),(17,16,‘G‘,15.00)
CREATE TABLE dbo.Cities
(
cityid char(3) not null primary key,
city varchar(30) not null,
region varchar(30) null,
country varchar(30) not null
);
create table dbo.Roads
(
city1 char(3) not null references dbo.Cities,
city2 char(3) not null references dbo.Cities,
distance int not null,
primary key(city1,city2),
check(city1<city2),
check(distance>0)
);
insert into dbo.Cities (cityid ,city,region ,country ) values(‘FAI‘,‘atlanta‘,‘GA‘,‘USA‘),(‘ANC‘,‘CHICAGO‘,‘IL‘,‘USA‘),(‘SFO‘,‘DENVER‘,‘CO‘,‘USA‘),(‘SEA‘,‘DENVER‘,‘CO‘,‘USA‘),(‘JFK‘,‘DENVER‘,‘CO‘,‘USA‘),(‘MSP‘,‘DENVER‘,‘CO‘,‘USA‘)
insert into dbo.Roads (city1 ,city2,distance ) values(‘SEA ‘,‘JFK‘,336),(‘SEA‘,‘MSP‘,3376),(‘SEA‘,‘IAH‘,3736),(‘SEA‘,‘MCI‘,3356),(‘DEN‘,‘MIA‘,3536),(‘DEN‘,‘MJP‘,3336),(‘DEN‘,‘IAH‘,336),(‘DEN‘,‘MCI‘,3376)
DECLARE @ROOT AS INT =1;
WITH SUBS
as
(
select EMPID,EMPNAME,0 AS LVl,
CAST(‘.‘+CAST(EMPID AS VARCHAR(10))+‘.‘ AS VARCHAR(max)) as path, 0 as cycle from dbo.EMPLOYEE
where empid [email protected]
union all
select c.empid, c.empname, p.LVl +1, cast (p.path + cast (c.empid as varchar(10))+‘.‘ as varchar(max)),
case when p.path like ‘%.‘+cast(c.empid as varchar(10))+‘.%‘ then 1 else 0 end
from subs as p join dbo.EMPLOYEE as c on c.mgrid =p.empid and p.cycle =0
)
select path,* from subs where
cycle =1;
以上是关于sql 图 ,树,层次的主要内容,如果未能解决你的问题,请参考以下文章
二叉树层次遍历(剑指Offer面试题32:从上到下打印二叉树)
Python使用matplotlib可视化树状图层次聚类系统树图树状图根据给定的距离度量将相似点分组在一起并根据点的相似性将它们组织成树状图链接起来(Dendrogram)