| Author |
Topic |
|
getur.srikanth@gmail.com
Yak Posting Veteran
77 Posts |
Posted - 2009-02-12 : 23:45:22
|
| DepartmentID | DepartmentName | ParentDepartmentID 42 | Loss Mitigation | 1625 | Information Technology | 1816 | Servicing | 3218 | Shared Services | 3232 | Bank Of America | NULL56 | Foreclosure | 1659 | Bankruptcy | 16From the above table I need to show the "List of the DepartmentNames in a hierarchical fashion. Start with the Departments that do not have a parent Department" |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-02-13 : 00:23:56
|
| try like this ;with cte(id,deptname,parentid,parentdept)as(select DepartmentID,DepartmentName,ParentDepartmentID,DepartmentName from urtableunion allselect t.DepartmentID,t.DepartmentName,t.ParentDepartmentID,c.deptnamefrom urtable tinner join cte c on c.id = t.ParentDepartmentID )select distinct * from cte where deptname <> parentdept |
 |
|
|
raky
Aged Yak Warrior
767 Posts |
Posted - 2009-02-13 : 00:30:49
|
| Hi ,Is this is what you want declare @temp table ( DepartmentID int, DepartmentName varchar(256), ParentDepartmentID int )insert into @temp select 42 , 'Loss Mitigation' , 16 union all select 25 , 'Information Technology' , 18 union all select 16 , 'Servicing' , 32 union all select 18 , 'Shared Services' , 32 union all select 32 , 'Bank Of America' , NULL union all select 56 , 'Foreclosure' , 16 union all select 59 , 'Bankruptcy' , 16SELECT * FROM @TEMP ORDER BY CASE WHEN ParentDepartmentID IS NULL THEN 0 ELSE 1 ENDIf not Please send the expected output... |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-02-13 : 01:25:05
|
| [code]declare @test table(DepartmentID int, DepartmentName varchar(50), ParentDepartmentID int)insert into @testselect 42,'Loss Mitigation',16 union allselect 25 ,'Information Technology', 18 union allselect 16 ,'Servicing', 32 union allselect 18 ,'Shared Services', 32 union allselect 32 ,'Bank Of America', NULL union allselect 56 ,'Foreclosure', 16 union allselect 59 ,'Bankruptcy', 16;with cte(id,deptname,parentid,parentdept,path,level)as(select DepartmentID,DepartmentName,ParentDepartmentID,cast(NULL as varchar(50)),CAST(DepartmentID AS varchar(max)),0 from @test where ParentDepartmentID is nullunion allselect t.DepartmentID,t.DepartmentName,t.ParentDepartmentID,c.deptname,CAST(t.DepartmentID AS varchar(10))+','+c.path,level+1from @test tinner join cte c on c.id = t.ParentDepartmentID )select * from cte order by leveloutput-----------------------------------------------------id deptname parentid parentdept path level32 Bank Of America NULL NULL 32 016 Servicing 32 Bank Of America 16,32 118 Shared Services 32 Bank Of America 18,32 125 Information Technology 18 Shared Services 25,18,32 242 Loss Mitigation 16 Servicing 42,16,32 256 Foreclosure 16 Servicing 56,16,32 259 Bankruptcy 16 Servicing 59,16,32 2[/code] |
 |
|
|
|
|
|