Соотнесите подзапрос, или вы можете использовать LEAD
.
select PolicyNumber,
QuoteID,
CoverageType,
ClaimType,
case when ClaimType = ' ' then (
select top 1 ClaimType
from @ClaimType c
where
x.PolicyNumber = c.PolicyNumber
and x.CoverageType = c.CoverageType
order by QuoteID desc
)
else ClaimType End as ClaimType1
from @ClaimType x
select
PolicyNumber
,QuoteID
,CoverageType
,ClaimType
,ClaimType1 = case when ClaimType = '' or ClaimType is null then lead(ClaimType) over (partition by PolicyNumber, CoverageType order by QuoteID) else ClaimType end
from @ClaimType
Если есть несколько пробелов или разрывы шаблона, когда QuoteID = 2
не тот, который заполнен, я бы какпредложение where для подзапроса.Обратите внимание на добавленную мной дополнительную строку и добавление предложения where.
declare @ClaimType table (PolicyNumber varchar(50), QuoteID int, CoverageType varchar(50), ClaimType varchar(100))
insert into @ClaimType values ('00001',1, 'CGL', ' '),
('00001',2, 'CGL', 'Occurrence'),
('00002',1, 'CPL', ' '),
('00002',2, 'CPL', 'Occurrence-Pollution'),
('00002',3, 'CPL', '') --added this row
select PolicyNumber,
QuoteID,
CoverageType,
ClaimType,
case when ClaimType = ' ' then (
select top 1 ClaimType
from @ClaimType c
where
x.PolicyNumber = c.PolicyNumber
and x.CoverageType = c.CoverageType
and c.ClaimType != '' --added this clause
order by QuoteID desc
)
else ClaimType End as ClaimType1
from @ClaimType x