首页 > 解决方案 > 在同一个表中嵌套 SQL

问题描述

请查找下表数据。

转表

唯一身份 孩子 家长
1 40647 40643
2 40645 40644
3 42742 42741
4 40646 40643
5 40643 40642
6 42741 42740
7 40644 40642
8 40643 40642
9 42740 40644
10 40644 40642

优惠表

唯一身份 HProp 等级
1 40647 70
2 40645 70
3 42742 20
4 40646 70
5 40643 80
6 42741 40
7 40644 80
8 40643 80
9 42740 70
10 40644 80

下面是编写的 SQL,它对同一个表有多个连接。有没有其他方法可以做到这一点,因为上述连接将继续另外 6 次。如果我不知道父级和子级,我该如何自动化呢?

请帮我解决一下这个。

Select
Case when IV.level=80 then IV.Code
     When IV1.level=80 then IV1.Code
     When IV2.level=80 then IV2.Code
     When IV3.level=80 then IV3.Code else '' End as FinalCode,
Case when IV.level=80 then IV.level
     When IV1.level=80 then IV1.level
     When IV2.level=80 then IV2.level
     When IV3.level=80 then IV3.level else '' End as Finallevel
from Offe FD
left join tran FT on FD.Hprop=FT.Child
left join Offe IV on IV.Hprop=FT.Parent  
left join Tran FT1 on FT.Parent=FT1.Child
left join Offe IV1 on FT1.Parent=IV1.OffeID 
left join Tran FT2 on FT1.Parent=FT2.Child
left join Offe IV2 on FT2.Parent=IV2.OffeID 
left join Tran FT3 on FT2.Parent=FT3.Child
left join Offe IV3 on FT3.Parent=IV3.OffeID 

标签: sqlsql-server

解决方案


您没有包含特定的预期结果,并且您的示例中并不清楚您想要的结果。无论如何,一个简单的递归 CTE 将自动在多个级别“走图”。

您可能需要添加一些过滤以选择特定的行,并进行一些后处理以根据需要显示/格式化数据,但查询应采用一般形式:

with
n as (
  select o.level, o.code, t.parent
  from offe o
  join tran t on t.child = o.hprop
 union all
  select o.level, o.code, t.parent
  from n
  join offe o on o.hprop = n.parent
  join tran t on t.child = o.hprop
)
select * from n -- tweak this SELECT as needed

推荐阅读