SQL产品包含其他

时间:2018-11-08 12:43:59

标签: sql sql-server

我的桌子看起来像这样

Parent  Child
10      2
10      3
10      4
10      5
11      2
11      3

您可以看到父级10也包含父级11,这就是我要在表中显示的内容,我想在其中添加包含该数据的行:

Parent  Child
10      2
10      3
10      4
10      5
**10        11**
11      2
11      3

1 个答案:

答案 0 :(得分:0)

您可以使用自联接和聚合来使“包含”其他父母的父母:

with t as (
      select t.*, count(*) over (partition by parent) as num_child
      from yourtable
     )
select tp2.parent, tp.parent
from t tp join
     t tp2
     on tp.child = tc2.child and tp.parent <> tp2.parent
group by tp.parent, tp2.parent, tp.num_child
having count(*) = tp.num_child  -- all children match

(此版本假定没有重复的行。)

然后您可以使用insert将它们添加到表中。

注意:如果两个父母有相同的孩子,则会插入两行。

相关问题