没有PRIOR code怎么做等级查询

[复制链接]
查看11 | 回复9 | 2008-11-24 01:01:03 | 显示全部楼层 |阅读模式
create table test_table
(
code varchar2(100),
name varchar2(100)
)
;
delete from TEST_TABLE;
insert into TEST_TABLE (CODE, NAME)
values ('001', '中国');
insert into TEST_TABLE (CODE, NAME)
values ('002', '美国');
insert into TEST_TABLE (CODE, NAME)
values ('00101', '北京');
insert into TEST_TABLE (CODE, NAME)
values ('00102', '天津');
insert into TEST_TABLE (CODE, NAME)
values ('00103', '河北');
insert into TEST_TABLE (CODE, NAME)
values ('0010301', '保定');
insert into TEST_TABLE (CODE, NAME)
values ('00103002', '石家庄');
要求查询出类似下面的数据(每级上级代码通过编码确认,没有相应的字段)
001 中国 1级有下级
00101 中国/北京2级没有下级
002 美国 1级没有下级
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
自己顶,那位高手能解决一下?
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
快下班了,基本和你要求的一样
Select b.childcode,a.name || '/' || b.childname names,b.lvl,b.is_leaf From test_table a,

(Select Substr(t.Code, 1, Length(t.Code) - 2) parentcode,t.Name childname,t.Code childcode,Level lvl,

case when exists(select 1 from test_table c where Substr(c.Code, 1, Length(c.Code) - 2)=t.code) then
'有下级'
else
'没有下级'
end as is_leaf

From Test_Table t

Start With t.code like '00_'

Connect By Prior t.Code=Substr(t.Code, 1, Length(t.Code) - 2)

) b
Where a.code(+)=b.parentcode;
[ 本帖最后由 asword 于 2009-1-22 17:03 编辑 ]
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
谢谢asword ,不过每个级别的长度不是固定的,所以Connect By Prior t.Code=Substr(t.Code, 1, Length(t.Code) - 2) 不能满足要求
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
各个级别的长度差不一样还是同一级别的长度也会不一样啊?
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
设计很怪,保定和石家庄竟然长度不一样。
SELECT code,name,LEVEL, DECODE(CONNECT_BY_ISLEAF,0,'有下级','没有下级')
FROM (select code, name, (select max(code) from test_table where code<t1.code and t1.code like code||'%') as parent

from test_table t1
)
START WITH parent IS NULL
CONNECT BY parent = PRIOR code;
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
select sys_connect_by_path(name,'/') from
(
select t.*,(select max(code) from test_table where t.code like code || '%' and code != t.code) parentid from test_table t
) connect by parentid = prior code start with parentid isnull
1
/中国
2
/中国/北京
3
/中国/天津
4
/中国/河北
5
/中国/河北/保定
6
/中国/河北/石家庄
7
/美国
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
to: newkid
//设计很怪,保定和石家庄竟然长度不一样。
不算怪异吧,用户自行编码,想怎么编就怎么编

SELECT code,name,LEVEL, DECODE(CONNECT_BY_ISLEAF,0,'有下级','没有下级')
FROM (select code, name, (select max(code) from test_table where code<t1.code and t1.code like code||'%') as parent

from test_table t1
)
START WITH parent IS NULL
CONNECT BY parent = PRIOR code;
好像没有问题,谢谢,我再试试
思路只能是自己构造parent?
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
这样没有规律的乱遍迟早会出问题。还是固定长度的好。
构造parent是最简单的办法了。
回复

使用道具 举报

千问 | 2008-11-24 01:01:03 | 显示全部楼层
大过年的,向你这种愿意帮助别人的人致敬,祝春节愉快
回复

使用道具 举报

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

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行