日期:2014-05-19  浏览次数:20515 次

裸体跪求SQL递归的一条语句...
在数据库中的存储数据如下:

编码             名称
---------------
1001     a
1002               b
1002001     c
1002001001   d
1002002     e
1002003     f
1003     g

现需求得结果为:
编码             名称
---------------
1001     a
1002001001   d
1002002     e
1002003     f
1003     g

呵呵,就是只取编码中最底层的数据.谢谢各位达人了,分不够另加

------解决方案--------------------
create table T(编码 varchar(20), 名称 char(1))
insert T select '1001 ', 'a '
union all select '1002 ', 'b '
union all select '1002001 ', 'c '
union all select '1002001001 ', 'd '
union all select '1002002 ', 'e '
union all select '1002003 ', 'f '
union all select '1003 ', 'g '


select * from T
where 编码 in
(
select distinct 编码=(select max(编码) from T where 编码 like A.编码+ '% ') from T as A
)

--result
编码 名称
-------------------- ----
1001 a
1002001001 d
1002002 e
1002003 f
1003 g

(5 row(s) affected)