SQL 查询:在结果中添加"HasChild"列



我有一个我认为很简单的问题,但答案是逃避我。我有一个"父"列与表中的其他记录相关的单个表。我要做的是一个选择语句,在我的结果中有一个"HasChild"位列。例如,如果我的表是这样的:

<>之前ID | ParentID1 | null2 | 13 | 24 | null5 | 46 | 1之前

然后我正在寻找一个选择,返回这些结果:

<>之前ID | ParentID | HasChild1 | null | true2 | 1 | true3 | 2 | false4 | null | true5 | 4 | false6 | 1 | false之前如往常一样,非常感谢帮助。
select
  x.ID,
  x.ParentId,
  case exists (select 'x' from YourTable y where y.ParentId = x.Id) then
    true
  else
    false
  end as HasParent
from
  YourTable x

也许你可以省略这个箱子,但我不确定:

select
  x.ID,
  x.ParentId,
  exists (select 'x' from YourTable y where y.ParentId = x.Id) as HasParent
from
  YourTable x

最新更新