求一 查询语句?

[复制链接]
查看11 | 回复7 | 2011-11-1 16:21:15 | 显示全部楼层 |阅读模式
表:
Create table tt (id int, name varchar(20),parent_id int)
go
insert tt select 1,'name1', null
union all select 2,'name2',null
union all select 3,'name3',1
union all select 4,'name4',2
union all select 5,'name5',1
union all select 6,'name6',2
union all select 7,'name7',3
union all select 8,'name8',4
go
需要得到这样的分层次的结果:
id name
---------------------------
1/1, name1
2/3, name3
3/7, name7
2/5, name5
1/2, name2
2/4, name4
3/8, name8
2/6, name6
查询语句该怎么写?
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
看不明白,结果是怎么出来的。
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
要得到这样的结果,查询语句该怎么写?
id name
---------------------------
1, name1
3, name3
7, name7
5, name5

2, name2
4, name4
8, name8
6, name6
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
select id,name from tablename where id notin(select id=2*id from tablename)
select id,name from tablename where id in(select id=2*id from tablename)
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
楼主的意思要安级次关系排序显示某一根下的全部节点
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
所谓的层次不是很清楚
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
4楼说出了我的真实要求。
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
在网上找到答案了。公布如下:
create function get_detail(@id int)
returns @t table(id int,name varchar(20),Parent_id int,level int,sort varchar(300))
as
begin

declare @lev int

set @lev=1

insert @t select id,name,Parent_id,@lev,right(1000+id,4)

from tt where id=@id

while @@rowcount>0

begin

set @lev=@lev+1
insert @t select a.id,a.name,a.Parent_id,@lev,sort+right(1000+a.id,4)
from tt a ,@t b where a.Parent_id=b.id and level=@lev-1

end

return
end
进行查询:
select id,name,parent_id from get_detail(1) order by sort
得到结果。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行