2016-07-27 45 views
0

樹型表的查詢我有3個表即是這樣的關係:需要對T-SQL

enter image description here

樹被加入本身使用的ParentId爲外鍵。樹和所有者表通過xrefOwnerTree表具有多對多關係。

我想寫一個查詢/函數,我給它一個樹ID,它給了我一個最近在層次結構(向上)的OwnerId。

這是我到目前爲止有:

WITH c (TreeId, Parentid, level, BranchName, OwnerId) as 
(
    SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId 
    FROM Tree t 
    JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId 
    JOIN Owner o ON ot.OwnerId = o.OwnerId 
    WHERE Parentid is null 

    UNION ALL 

    SELECT t2.TreeId, t2.parentid, c.level + 1, t2.BranchName, o2.OwnerId 
    FROM Tree t2 
    JOIN xrefOwnerTree ot2 ON t2.TreeID = ot2.TreeId 
    JOIN Owner o2 ON ot2.OwnerId = o2.OwnerId 
    INNER JOIN c ON c.TreeId = t2.parentid 
) 
SELECT * FROM t WHERE t.TreeId = 32800 and t.OwnerId is not NULL 

它返回0的記錄。它應該返回回1.

樣本數據:

select * from tree where treeid = 32800 
union 
select * from tree where treeid = 32646 
union 
select * from tree where treeid = 32645 
union 
select * from tree where treeid = 32619 
union 
select * from tree where treeid = 31459 
union 
select * from tree where treeid = 31458 

enter image description here

select * from owner 

enter image description here

select * from dbo.xrefOwnerTree where treeid = 31459 

enter image description here

WITH c (TreeId, Parentid, level, BranchName, OwnerId) as 
(
    SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId 
    FROM Tree t 
    JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId 
    JOIN Owner o ON ot.OwnerId = o.OwnerId 
    WHERE Parentid is null 

    UNION ALL 

    SELECT t2.TreeId, t2.parentid, c.level + 1, t2.BranchName, o2.OwnerId 
    FROM Tree t2 
    JOIN xrefOwnerTree ot2 ON t2.TreeID = ot2.TreeId 
    JOIN Owner o2 ON ot2.OwnerId = o2.OwnerId 
    INNER JOIN c ON c.TreeId = t2.parentid 
) 
SELECT * FROM c 

enter image description here

SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId 
FROM Tree t 
JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId 
JOIN Owner o ON ot.OwnerId = o.OwnerId 
WHERE Parentid is null 

enter image description here

+1

您可能想要更改錨定成員,使其不使用't'作爲別名,因爲它已經是CTE的名稱。如果從最終的'SELECT'中刪除'WHERE'子句,你會得到什麼?如果您只是執行CTE的主播成員,您會得到什麼?你可以發佈一小組示例數據來說明問題嗎?請閱讀[this](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/)瞭解一些關於改善問題的提示。 – HABO

+0

別名已更改。 當我刪除where子句時,它什麼也不給我。 – Gerson

回答

0

我沒有自己的表。我建議你有一個像這樣的檢查您的聯盟之一:

首先檢查它:

SELECT t.TreeId, t.Parentid, 0 as level, BranchName, o.OwnerId 
    FROM Tree t 
    JOIN xrefOwnerTree ot ON t.TreeID = ot.TreeId 
    JOIN Owner o ON ot.OwnerId = o.OwnerId 
    WHERE Parentid = 0 

然後第二個..

希望它可以幫助。

+0

當我運行第一個查詢時,我一無所獲(請參閱更新中的示例數據)。我無法孤立地運行第二個,因爲它依賴於「with」語句 – Gerson

+0

耶看到它,你想要什麼結果爲特定的第一個查詢? –