[英]How to display the Parent next child rows in SQl server
I want to rearrange the parent row next child rows in sql server like below 我想像下面这样在SQL Server中重新排列父行的下一个子行
Rownum name parentid
--------------------
1 sathish null
2 kumar null
3 sk 1
4 sk 1
5 sk 2
now i want to rearrange like below 现在我想像下面重新排列
Rownum name parentid
--------------------
1 sathish null
3 sk 1
4 sk 1
2 kumar null
5 sk 2
pls help with sql query 请帮助SQL查询
Try this, 尝试这个,
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
check THIS IT WILL WORK 检查这将工作
SELECT *
FROM YOURTABLE
ORDER BY COALESCE(parentid ,Rownum ),Rownum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.