在SQL中的Recurssive查询中需要帮助

时间:2015-09-14 14:01:57

标签: sql sql-server tsql

我在sql递归查询中需要帮助,例如,我提供带有插入脚本的示例表。

CREATE   TABLE Details(
parentid varchar(10), DetailComponent varchar(10) , DetailLevel int)
GO

INSERT INTO Details 
SELECT '','7419-01',0 union all
SELECT '7419-01','44342-00',1 union all
SELECT '7419-01','45342-00',1 union all
SELECT '7419-01','46342-00',1 union all
SELECT '7419-01','47342-00',1 union all
SELECT '7419-01','48342-00',1 union all
SELECT '7419-01','49342-00',1 union all
SELECT '7419-01','50342-00',1 union all
SELECT '50342-00','51342-00',2 union all
SELECT '7419-01','52342-00',1 union all
SELECT '52342-00','54342-00',2 union all
SELECT '54342-00','54442-00',3 union all
SELECT '54342-00','54552-00',3 union all
SELECT '54552-00','R34S-54',4 union all
SELECT '54552-00','R123-54',4 union all
SELECT '54552-00','R111-54',4 union all
SELECT 'R111-54','R222-54',5 union all
SELECT 'R222-54','52342-00',6 union all
SELECT '7419-01','TEST34-00',1 union all
SELECT 'TEST34-00','445334-00',2 union all
SELECT '445334-00','52342-00',3  union all
SELECT '7419-01','1111-00',1 union all
SELECT '7419-01','1111-00',1 union all
SELECT '1111-00','52342-00',2 
GO

SELECT * FROM Details

从上表数据中我想要一个搜索查询,例如,如果我使用“52342-00”搜索数据,我希望使用CTE输出低于格式。

NULL,'7419-01',0
'7419-01','52342-00',1
'7419-01','52342-00',1
'52342-00','54342-00',2
'54342-00','54552-00',3
'54552-00','R111-54',4
'R111-54','R222-54',5
'R222-54','52342-00',6

请提供建议。

1 个答案:

答案 0 :(得分:1)

要获得输出,您必须在cte中指定DetailLevel,因为只搜索“52342-00”将返回多个结果。

这将为您提供结果,而无需指定具体的DetailLevel:

;with cte as (
select d.parentid,d.DetailComponent,d.DetailLevel as DetailLevel
from @Details d
  inner join (select distinct DetailComponent, MAX(DetailLevel) as DetailLevel from @Details
                group by DetailComponent) d2
    on d.DetailComponent = d2.DetailComponent
    and d.DetailLevel = d2.DetailLevel
where d.DetailComponent = '52342-00'
union all
select a.parentid, a.DetailComponent,a.DetailLevel
from @Details a
  inner join cte b
    on a.DetailComponent = b.parentid
    and a.DetailLevel < b.DetailLevel
  )

select * from cte
order by DetailLevel asc