复杂的sql查询来获取JIT spacetree的数据

时间:2013-10-30 07:05:45

标签: sql sql-server sql-server-2008

我需要为下面的spacetree构建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也具有一些子节点,这意味着它们是一些其他子节点的root / parentnode。意味着查询将是: -

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的结果。

任何人都可以帮助我吗?

提前致谢

1 个答案:

答案 0 :(得分: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