如何在SQl服务器中显示Parent下一个子行

时间:2015-02-26 12:35:43

标签: sql sql-server

我想在sql server中重新排列父行的下一行子行,如下所示

Rownum name parentid
--------------------

1     sathish null

2     kumar   null

3     sk      1

4     sk      1

5     sk      2

现在我想重新排列如下

Rownum name parentid
--------------------
1      sathish  null

3      sk       1

4      sk       1

2      kumar    null

5      sk       2

请帮助sql查询

2 个答案:

答案 0 :(得分:0)

试试这个,

Declare @t table(Rownum int, name varchar(100),parentid int)
insert into @t values (1,'sathish', null),(2,'kumar',null)
,(3,'sk',1),(4,'sk',1),(5,'sk',2)

;WiTH CTE as
(
 select *,rank()over( order by rownum) rn from @t where parentid is null
),
CTE1 as
(
select * from CTE
union all

select a.*,b.rn from CTE1 B 
inner join @t a on a.parentid=b.Rownum
where a.parentid is not null

)
select * from cte1 order by  rn

答案 1 :(得分:0)

检查它是否可行

SELECT *
FROM YOURTABLE 
ORDER BY COALESCE(parentid ,Rownum ),Rownum