需要对T-SQL

问题描述:

树型表的查询我有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

我没有自己的表。我建议你有一个像这样的检查您的联盟之一:

首先检查它:

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

耶看到它,你想要什么结果为特定的第一个查询? –