对不起我的问题标题,我找不到更好的名字。
这是我的表:
Project_ID ParentProject Projecttype
----------------------------------------
20.003 20.001 P
20.001 20 P
20 NULL V
21.001 21 P
21 NULL V
我想用'upperparentproject'来选择我的所有项目。我想使用Projecttype = 'P'
ParentProject
和Projecttype = 'V'
搜索所有项目。所以这必须是我的结果:
Project_ID ParentProject
--------------------------
20.003 20
20.001 20
21.001 21
这可能在SELECT
声明中还是有其他方法可以执行此操作?
答案 0 :(得分: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