Hi @ahmed salah ,
Please refer to:
create table #replace
(
PartIdc int,
PartIdx int,
)
insert into #replace(PartIdc,PartIdx)
values
(1211,1300),
(2000,2200),
(3000,3100),
(4150,4200)
create table #FeatureNameandValues
(
PartId int,
FeatueName nvarchar(20),
FeaatureValue int
)
insert into #FeatureNameandValues(PartId,FeatueName,FeaatureValue)
values
(1211,'Weight',5),
(2000,'Tall',20),
(3000,'Weight',70),
(4150,'Tall',190),
(1211,'Tall',80),
(1300,'Weight',10),
(3100,'Size',150),
(4200,'Tall',130),
(1300,'Tall',20)
;with cte
as(select FeatueName,PartIdc,PartIdx from #replace cross apply (select distinct FeatueName from #FeatureNameandValues)t
)
,cte2 as
(select c.FeatueName,c.PartIdc,c.PartIdx,case when c.PartIdc=f.PartId and c.FeatueName=f.FeatueName then f.FeaatureValue end FeaatureValueC,
case when c.PartIdx=f.PartId and c.FeatueName=f.FeatueName then f.FeaatureValue end FeaatureValueX,
row_number() over(partition by c.PartIdc,c.FeatueName order by c.PartIdc,c.FeatueName) rn
from cte c
left join #FeatureNameandValues f
on (c.PartIdc=f.PartId and c.FeatueName=f.FeatueName) or (c.PartIdx=f.PartId and c.FeatueName=f.FeatueName))
,cte3 as
(select a.FeatueName,a.PartIdc,a.PartIdx,a.FeaatureValueC,a.FeaatureValueX FeaatureValueX1 ,a.rn,
lead(b.FeaatureValueX,1) over(partition by a.PartIdc,a.FeatueName order by a.PartIdc,a.FeatueName) FeaatureValueX2
from cte2 a
left join cte2 b
on a.FeatueName=b.FeatueName and a.PartIdc=b.PartIdc and a.rn=b.rn)
select FeatueName,PartIdc,PartIdx,FeaatureValueC,case when FeaatureValueX1=150 then FeaatureValueX1 else FeaatureValueX2 end FeaatureValueX
from cte3
where rn<2
order by PartIdc,FeatueName
drop table #replace
drop table #FeatureNameandValues
Best Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.