4

我正在使用 SQL Server 2008。我有一个这样的表:

UnitId ParentId  UnitName
---------------------------
1        0       FirstUnit
2        1       SecondUnit One  
3        1       SecondUnit Two
4        3           B
5        2           C
6        4           D
7        6           E
8        5           F

我想获得记录的第二个父母。例如:

如果我选择等于 8 的单元 id,它会给我带来等于 2 的单元 id。它需要是 SecondUnit One。或者如果我选择等于 7 的单元 id,它会给我带来等于 3 的单元 id。它需要是 SecondUnit 2。

如何以这种方式编写 SQL 查询?

4

2 回答 2

6

我花了一段时间,但这里是:)

with tmp as (
  select unitId, parentId, unitName, 0 as iteration
  from t
  where unitId = 7
  union all
  select parent.unitId, parent.parentId, parent.unitName, child.iteration + 1
  from tmp child
  join t parent on child.parentId = parent.unitId
  where parent.parentId != 0
)
select top 1 unitId, parentId, unitName from tmp
order by iteration desc

这也是一个可以玩的小提琴。

于 2012-04-13T06:30:27.807 回答
1
SELECT t.*, tParent1.UnitId [FirstParent], tParent2.UnitId [SecondParent]
FROM Table t
    LEFT JOIN Table tParent1 ON t.ParentId = tParent1.UnitId
    LEFT JOIN Table tParent2 ON tParent1.ParentId = tParent2.UnitId
WHERE t.UnitId = <Unit ID search here>
    AND NOT tParent2.UnitId IS NULL

编辑:如果您希望返回结果,即使它们没有第二个父项,也可以省略 WHERE 子句的第二部分。

于 2012-04-13T06:28:51.163 回答