有个统计求不出来。谁能帮帮我
我现在数据库出现这样的数据id productid parentid menuname 四个字段。具体数据如下:
1 73 0 xxxxxx
2 73 0 xxxxxxx
3 73 1 xxxxxxx
4 73 1 xxxxxxx
5 73 2 xxxxxxx
6 73 2 xxxxxxx
7 73 3 xxxxxxx
8 73 3 xxxxxxx
9 73 3 xxxxxxx
10 73 4 xxxxxxx
11 73 4 xxxxxxx
12 73 4 xxxxxxx
13 73 4 xxxxxxx
14 73 4 xxxxxxx我要如何求出末节点个数呢。
就是没有父级的个数
急了。帮帮忙吧。。不能修改数据结构了。
我现在数据库出现这样的数据id productid parentid menuname 四个字段。具体数据如下:
1 73 0 xxxxxx
2 73 0 xxxxxxx
3 73 1 xxxxxxx
4 73 1 xxxxxxx
5 73 2 xxxxxxx
6 73 2 xxxxxxx
7 73 3 xxxxxxx
8 73 3 xxxxxxx
9 73 3 xxxxxxx
10 73 4 xxxxxxx
11 73 4 xxxxxxx
12 73 4 xxxxxxx
13 73 4 xxxxxxx
14 73 4 xxxxxxx我要如何求出末节点个数呢。
就是没有父级的个数
急了。帮帮忙吧。。不能修改数据结构了。
解决方案 »
- 求一个数据转换的查询语句
- 救助。。SQL基础。
- CListCtrl 如何根据字体设置行的高度?
- 能建立如下约束吗?
- 关于SQL server 2000 系统表的导出问题,急!!!
- 如何用ASP显示数据库中以 OLE 对象方式存储的 WROD 文件?
- 关于select * into b1 from b2的问题?
- 88分求教,有谁能把帮我把这个SQL语句优化一下呀?,表记录有40万条运行好慢呀。
- 数据库中视图怎么用?触发器怎么用?
- 菜鸟的触发器问题-再线急等
- 可否在 触发器中向触发器所属表中插入一条记录或者删除一条记录, sqlserver
- select * into from 记录顺序怎么不一致? 万分火急!
create table BOM(ID INT,PID INT,MSG VARCHAR(1000))
insert into BOM select 1,0,NULL
insert into BOM select 2,1,NULL
insert into BOM select 3,1,NULL
insert into BOM select 4,2,NULL
insert into BOM select 5,3,NULL
insert into BOM select 6,5,NULL
insert into BOM select 7,6,NULL
go--创建用户定义函数用于取每个父节点下子节点的采购配置信息
create function f_getChild(@ID VARCHAR(10))
returns @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
as
begin
declare @i int
set @i = 1
insert into @t select ID,PID,@i from BOM where PID = @ID
while @@rowcount<>0
begin
set @i = @i + 1
insert into @t
select
a.ID,a.PID,@i
from
BOM a,@t b
where
a.PID=b.ID and b.Level = @i-1
end
return
end
go--执行查询
select ID from dbo.f_getChild(3)
go--输出结果
/*
ID
----
5
6
7
*/--删除测试数据
drop function f_getChild
drop table BOM创建用户定义函数,每个子节点de父节点的信息
--生成测试数据
create table BOM(ID int,parentID int,sClassName varchar(10))
insert into BOM values(1,0,'1111' )
insert into BOM values(2,1,'1111_1' )
insert into BOM values(3,2,'1111-1-1' )
insert into BOM values(4,3,'1111-1-1-1')
insert into BOM values(5,1,'1111-2' )go--创建用户定义函数,每个子节点de父节点的信息
create function f_getParent(@ID int)
returns varchar(40)
as
begin
declare @ret varchar(40) while exists(select 1 from BOM where ID=@ID and parentID<>0)
begin
select @ID=b.ID,@ret=','+rtrim(b.ID)+isnull(@ret,'')
from
BOM a,BOM b
where
a.ID=@ID and b.ID=a.parentID
end
set @ret=stuff(@ret,1,1,'')
return @ret
end
go--执行查询
select ID,isnull(dbo.f_getParent(ID),'') as parentID from BOM
go--输出结果
/*
ID parentID
----------- ----------------------------------------
1
2 1
3 1,2
4 1,2,3
5 1
*/--删除测试数据
drop function f_getParent
drop table BOM
go
where not exists (
select 1 from tab
where productid=a.productid and parentid=a.id
)
select * from tab a
where not exists (
select 1 from tab
where parentid=a.id
)
--求所有顶级节点
select * from tab a
where not exists (
select 1 from tab
where a.parentid=id
)