读书人

sql中行数据层级显示,该怎么处理

发布时间: 2012-09-13 09:51:52 作者: rapoo

sql中行数据,层级显示
列明:一级 二级 三级
值 :a b e
a f
c d x
c h

显示:
级别 值
1 a
2 b
3 e
2 f
1 c
2 d
3 x
2 h



[解决办法]

SQL code
declare @test table(一级 varchar(1), 二级 varchar(1), 三级 varchar(1))insert into @testselect 'a', 'b', 'e' union allselect 'a', 'f', '' union allselect 'c', 'd', 'x' union allselect 'c', 'h', '';with cte as(    select row_number() over(order by 一级) rn,* from @test),t as(    select row_number() over(order by rn,级别)id,级别,值 from    (        select rn,一级 as 值,1 级别 from cte        union all        select rn,二级,2 from cte        union all        select rn,三级,3 from cte    )t    where 值<>'')select 级别,值 from t awhere not exists(select 1 from t where a.id>id and 级别=a.级别 and 值=a.值)order by id/*级别          值----------- ----1           a2           b3           e2           f1           c2           d3           x2           h*/ 

读书人网 >SQL Server

热点推荐