it should be ;with cte as ( select AccountCode,ParentAccCode,1 as [Level] ,CAST(AccountCode as varchar(max)) AS [Path] from level union all select L.AccountCode,L.ParentAccCode,[Level]+1 as [Level] ,cast([Path] + '/' + cast(L.AccountCode AS varchar(100)) as varchar(max)) from level L inner join cte C on L.AccountCode= C. ParentAccCode ) select val,Level from ( select dense_rank() over (partition by left([Path],charindex('/',[Path] + '/')-1) order by Level desc) AS Rnk, left([Path],charindex('/',[Path] + '/')-1) as val,Level from cte )t Where Rnk <= 2
------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/