0

对不起我的问题标题,我找不到更好的名字。

这是我的桌子:

Project_ID   ParentProject   Projecttype
----------------------------------------
20.003       20.001          P
20.001       20              P
20           NULL            V
21.001       21              P
21           NULL            V

我想用它的“上父项目”来选择我所有的项目。Projecttype = 'P'我想用ParentProjectwith搜索所有项目Projecttype = 'V'。所以这必须是我的结果:

Project_ID   ParentProject
--------------------------
20.003       20        
20.001       20                
21.001       21         

这可能在SELECT声明中还是有其他方法可以执行此操作?

4

1 回答 1

0

尝试这个:

 select *,row_number() over (order by (select 0)) as rn  into tbl1 from table1

Declare @mn int,@mx int
Declare @mn1 int,@mx1 int
Declare @prjid float,@prntid varchar(10)
DECLARE @result TABLE(prjID float,prentID varchar(10))

select @mn=MIN(rn),@mx=MAX(rn) from tbl1

WHILE(@mn<=@mx)
BEGIN
select @prjid=Project_id,@prntid=ParentProject from tbl1 where rn=@mn and ProjectType='P'
select @mn1=MIN(rn),@mx1=MAX(rn) from tbl1

WHILE(@mn1<=@mx1)
BEGIN
select @prntid=CASE WHEN ParentProject IS NOT NULL then ParentProject else @prntid end from tbl1 where Project_id=@prntid and rn = @mn1
SET @mn1=@mn1+1
END

INSERT INTO @result 
values(@prjid,@prntid) 

SET @mn=@mn+1
END
select distinct * from @result 
于 2013-04-24T10:04:32.723 回答