如何使用 CTE 從分層視圖中獲取元素 (How to get elements from a hierarchical view with CTE)


問題描述

如何使用 CTE 從分層視圖中獲取元素 (How to get elements from a hierarchical view with CTE)

I have a table that store recursive records through two fields: ID and PARENTID.

I have a functionality that can associate a parent to an element of the tree. When I select the elements that can be "parent" of myself I shall obviously exclude from the resulting list all the elements which, directly or indirectly, depends on me but also the elements from which I already depend.

Let's make an example. Given the following sample hierarchy:

ID                  PARENT_ID
‑‑‑‑‑‑‑‑‑‑‑         ‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑‑
1                    NULL
2                    1
3                    NULL
4                    2
5                    1
6                    3

If I would like to find the elements that can be parent of element with ID = 4 I shall consider only elements 5 ‑ 3 ‑ 6 because they do not have any relation with the actual structure.

How can I get those elements with a CTE query?

‑‑‑‑‑

參考解法

方法 1:

Select *
into #tmp
From Tree2

;WITH Rollups AS (
    SELECT ID, Parent_Id
    FROM tree2 where ID=4
    UNION ALL
    SELECT parent.Id, parent.Parent_Id
    FROM tree2 parent 
    INNER JOIN Rollups child ON child.Id = parent.Parent_Id
)
Delete #tmp from Rollups where #tmp.ID=Rollups.ID

;WITH Rollups AS (
    SELECT ID, Parent_Id
    FROM tree2 where ID=4
    UNION ALL
    SELECT parent.Id, parent.Parent_Id
    FROM tree2 parent 
    INNER JOIN Rollups child ON child.Parent_Id = parent.Id
)
Delete #tmp from Rollups where #tmp.ID=Rollups.ID

Select * from #tmp
Drop Table #tmp 

(by Lorenzobummi)

參考文件

  1. How to get elements from a hierarchical view with CTE (CC BY‑SA 3.0/4.0)

#sql-server-2008 #sql-server #common-table-expression






相關問題

基於集合的插入到具有 1 到 0-1 關係的兩個表中 (Set based insert into two tables with 1 to 0-1 relation)

如何使用 CTE 從分層視圖中獲取元素 (How to get elements from a hierarchical view with CTE)

where 子句中使用等於和 IN 的 CASE 語句 (CASE Statement in where clause using equal to and IN)

與 SQL 服務器匯總匯總 - 但只有最後一個摘要? (Sum with SQL server RollUP - but only last summary?)

將範圍分組到範圍 (Group a range towards a range)

在 SQL Server 2008 中運行 WHILE 或 CURSOR 或兩者 (Running WHILE or CURSOR or both in SQL Server 2008)

按組中的最大值排序 (Order by the max value in the group)

使用存儲過程創建搜索函數 (Creating a Search Function, using stored procedure)

在 sql server 2008 中查詢最後費用日期 (Query for Last Fees Date in sql server 2008)

除了 SQL Server Profiler,還有什麼 SQL Server Profile? (What is SQL Server Profile aside from SQL Server Profiler?)

什麼是日期時間2? (What is datetime2?)

可以在這裡使用 Common Table 表達式來提高性能嗎? (Can Common Table expressions be used here for performance?)







留言討論