0

我需要为如下所示的空间树构建 json 字符串:- http://philogb.github.io/jit/static/v20/Jit/Examples/Spacetree/example2.code.html

目前我正在使用以下查询:-

SELECT BT.ParentID,BT.CustomerID,CU.firstname 
from BinaryTree BT INNER JOIN Customers CU on BT.CustomerID=CU.CustomerID
WHERE [ParentID] = 2
ORDER BY BT.ParentID,BT.CustomerID

它返回结果如下: -

ParentID   CustomerID  firstname
     2      100176         Bill
     2      115468        will

这里的意思是 2 是树的根元素,100176,115468 是子元素。但是这些子节点 100176 和 115468 也有一些子节点,这意味着这些是其他一些子节点的根/父节点。意味着查询将是:-

SELECT BT.ParentID,BT.CustomerID,CU.firstname 
from BinaryTree BT INNER JOIN Customers CU on BT.CustomerID=CU.CustomerID
WHERE [ParentID] = 100176
ORDER BY BT.ParentID,BT.CustomerID

100176 的结果:-

 ParentID   CustomerID  firstname
   100176    100222       J
   100176    348645       K

SELECT BT.ParentID,BT.CustomerID,CU.firstname 
from BinaryTree BT INNER JOIN Customers CU on BT.CustomerID=CU.CustomerID
WHERE [ParentID] = 115468        
ORDER BY BT.ParentID,BT.CustomerID

结果为 115468:-

 ParentID   CustomerID  firstname
  115468     154756       D
  115468     348480       L

但是我需要一个查询中的所有父母和孩子,例如:-

 ParentID   CustomerID  firstname
    2        100176       Bill
    2        115468       will
  100176     100222       J
  100176     348645       K
  115468     154756       D
  115468     348480       L

100176 和 115468 的子节点也可以有子节点,因此这些也应该是上述结果中 100222,348645 的结果。

有谁能够帮助我?

提前致谢

4

1 回答 1

1
WITH CustomerTree AS (
    SELECT ParentID
          ,CustomerID
          ,0 AS Level
    FROM BinaryTree
    WHERE ParentID = 2
  UNION ALL
    SELECT BinaryTree.ParentID
          ,BinaryTree.CustomerID
          ,CustomerTree.Level + 1 AS Level
    FROM BinaryTree
         INNER JOIN CustomerTree
            ON BinaryTree.ParentID = CustomerTree.CustomerID
)
SELECT CustomerTree.ParentID
      ,CustomerTree.CustomerId
      ,Customers.FirstName
FROM CustomerTree
     INNER JOIN Customers
         ON CustomerTree.CustomerID = Customers.CustomerID
于 2013-10-30T07:33:36.820 回答