2017-06-13 29 views
0

我有以下結構的表:SQL服務器 - 訂單數據層次從表

| ObjectID | ParentID | Description | Level | 
---------------------------------------------------- 
| 1000  | NULL  | Food   | 0  | 
| 1001  | 1000  | Fruit  | 1  | 
| 1002  | 1000  | Vegetable | 1  | 
| 1003  | 1001  | Apple  | 2  | 
| 1004  | 1001  | Banana  | 2  | 
| 1005  | 1002  | Cabbage  | 2  | 
| 1006  | 1002  | Spinach  | 2  | 
| 1007  | 1003  | Red   | 3  | 
| 1008  | 1003  | Green  | 3  | 
| 1009  | 1007  | Single  | 4  | 
| 1010  | 1007  | Bunch  | 4  | 
| 1011  | 1010  | Organic  | 5  | 
| 1012  | 1010  | Non-Organic | 5  | 

它基本上列出一個表中一羣具有層次的對象。 現在我需要能夠查詢此表,並提出基於單個ObjectID的層次結構。像這樣:

在這個例子中,我需要搶在「蘋果」層次的一切,這樣的結果集將是:

| ObjectID | ParentID | Description | Level | 
---------------------------------------------------- 
| 1003  | 1001  | Apple  | 2  | 
| 1007  | 1003  | Red   | 3  | 
| 1009  | 1007  | Single  | 4  | 
| 1010  | 1007  | Bunch  | 4  | 
| 1011  | 1010  | Organic  | 5  | 
| 1012  | 1010  | Non-Organic | 5  | 
| 1008  | 1003  | Green  | 3  | 

聲明本如何通過性命令行,其中直接子來在父母之後。

我真的很感謝幫助!謝謝!

+0

這個問題並沒有表現出任何的研究工作。 –

+0

[SQL Server遞歸查詢]的可能重複(https://stackoverflow.com/questions/3916597/sql-server-recursive-query) –

+0

此重複說明如何將Level包含在結果中:https:// stackoverflow .com/questions/14274942/sql-server-cte-and-recursion-example –

回答

0
Declare @Top int = 1003 --<< Set To NULL for Full Hier 

;with cteP as (
     Select [ObjectID] 
      ,[ParentId] 
      ,[Level] 
      ,[Description] 
      ,[Sequence] = cast(10000+Row_Number() over (Order by [ObjectID]) as varchar(500)) 
     From @YourTable 
     Where IsNull(@Top,-1) = case when @Top is null then isnull([ParentId] ,-1) else [ObjectID] end 
     Union All 
     Select r.[ObjectID] 
      ,r.[ParentId] 
      ,r.[Level] 
      ,r.[Description] 
      ,cast(concat(p.[Sequence],'.',10000+Row_Number() over (Order by r.[ObjectID])) as varchar(500)) 
     From @YourTable r 
     Join cteP p on r.[ParentId] = p.[ObjectID]) 
Select [ObjectID] 
     ,[ParentId] 
     ,[Description] 
     ,[Level] 
From cteP 
Order By [Sequence] 

返回

ObjectID ParentId Description Level 
1003  1001  Apple  2 
1007  1003  Red   3 
1009  1007  Single  4 
1010  1007  Bunch  4 
1011  1010  Organic  5 
1012  1010  Non-Organic 5 
1008  1003  Green  3 
+0

非常感謝!添加的位顯示嵌套的可讀性非常好! – Smiley

+0

@Smiley我懷疑你已經知道了。我編輯來鏡像你想要的結果。很高興它有幫助。 –

0

效仿聯機叢書:

https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql

USE AdventureWorks2012; 
GO 
WITH DirectReports(ManagerID, EmployeeID, Title, EmployeeLevel) AS 
( 
    SELECT ManagerID, EmployeeID, Title, 0 AS EmployeeLevel 
    FROM dbo.MyEmployees 
    WHERE ManagerID IS NULL 
    UNION ALL 
    SELECT e.ManagerID, e.EmployeeID, e.Title, EmployeeLevel + 1 
    FROM dbo.MyEmployees AS e 
     INNER JOIN DirectReports AS d 
     ON e.ManagerID = d.EmployeeID 
) 
SELECT ManagerID, EmployeeID, Title, EmployeeLevel 
FROM DirectReports 
ORDER BY ManagerID; 
GO