选择只能通过SQL Server中的父行找到的兄弟行的值

时间:2015-08-09 20:40:05

标签: sql sql-server

我只有一个名为Posts with 5 column的表(很像StackExchange Data Explorer)

Id, Score, PostTypeId, ParentId, AcceptedAnswerId 
1   5      1           null      3
2   3      1           null      5
3   9      2           1         null
4   3      2           1         null
....

如您所见,这些行有两个层次结构(Parents,Childs)。让我们说我想选择孩子(PostTypeId = 2)和每个我想加入兄弟的分数< / strong>目前父母已接受。已接受的兄弟ID只能在行的AcceptedAnswerId列中找到。父行可以通过我选择的子行的ParentId找到。是否有一种优雅的方式来做到这一点?

预期结果如下

 Id, Score, AcceptedScore
 3   9      9
 4   3      9
 ....

我的尝试(虽然它不会起作用并伤害我的眼睛和我的大脑):

select top 50 a.Id, a.Score, b.Score as AcceptedScore
from Posts as a
left join (
  select c.Score from Posts as c
  where c.Id = (
    select d.AcceptedAnswerId from Posts as d
    where d.Id = a.ParentId
  )
) as b
on b.ParentId = a.ParentId 
where a.PostTypeId = 2 

我得到的错误:

The multi-part identifier "a.ParentId" could not be bound. Invalid column name 'ParentId'.

1 个答案:

答案 0 :(得分:3)

这是一个有效的方法:

SELECT p1.Id, p1.Score, p3.Score AS AcceptedScore
FROM Posts p1 LEFT JOIN Posts p2
  ON p1.ParentId = p2.Id LEFT JOIN Posts p3
  ON p2.AcceptedAnswerId = p3.Id
WHERE p1.PostTypeId = 2

请参阅SQLFiddle