您好我想从此代码中获取以下内容如果有多个匹配项,请找到LearnStartDate = LearnDelFAMDateFrom的记录,否则请留空
select
ukprn, aimseqnumber, LearnRefNumber
,LearnDelFAMCode
,LearnDelFAMType
,LearnDelFAMDateFrom
,LearningStartDate
,CASE
when rn=1 then LearnDelFAMDateFrom
when rn <1 then ''
when (rn =1 and rn > 1) and (LearningStartDate = LearnDelFAMDateFrom) then LearnDelFAMDateFrom
else
''
end as LearnDelFAMDateFromMOD
--,CASE row_number() over(partition by d.LearnRefNumber,d.aimseqnumber order by LearnDelFAMDateFrom)
-- when 1 then LearnDelFAMDateFrom
-- when < 1 then ''
-- when > 1 and (LearningStartDate = LearnDelFAMDateFrom) then LearnDelFAMDateFrom
-- else ''
-- end as LearnDelFAMDateFromMOD2
,rn
--,LearnDelFAMDateTo
from
(select
d.ukprn,d.aimseqnumber,d.LearnRefNumber,LearnDelFAMCode,LearnDelFAMType
,convert(varchar(10),LearnDelFAMDateFrom) as LearnDelFAMDateFrom
,LearnDelFAMDateTo,LearningStartDate
,row_number() over(partition by d.LearnRefNumber,d.aimseqnumber order by LearnDelFAMDateFrom) rn
from d
left join rp
on
d.ukprn =rp.ukprn
and d.aimseqnumber=rp.AimSeqNumber
and d.LearnRefNumber=rp.LearnRefNumber
and LearnDelFAMCode=rp.ApprenticeshipContractType
left join aecld
on
d.ukprn =aecld.ukprn
and d.aimseqnumber=aecld.AimSeqNumber
and d.LearnRefNumber=aecld.learnrefnumber
where LearnDelFAMType='ACT'
) as ref
由于我不能使用大于或小于或等于符号,因此无法运行包含分区by的代码的注释部分。
如果我只是将case语句用于以下场景 当(rn = 1和rn> 1)和(LearningStartDate = LearnDelFAMDateFrom)然后LearnDelFAMDateFrom 这仅适用于rn> 1时的记录,当rn = 1时它不起作用。
答案 0 :(得分:0)
我建议使用CTE表来执行此任务,ROW_NUMBER()... AS将被解析,然后您可以在案例陈述中使用它
;WITH CTE_TEMP_TABLENAME AS
(
select
d.ukprn,d.aimseqnumber,d.LearnRefNumber,LearnDelFAMCode,LearnDelFAMType
,convert(varchar(10),LearnDelFAMDateFrom) as LearnDelFAMDateFrom
,LearnDelFAMDateTo,LearningStartDate
,row_number() over(partition by d.LearnRefNumber,d.aimseqnumber order by LearnDelFAMDateFrom) rn
from d
left join rp
on
d.ukprn =rp.ukprn
and d.aimseqnumber=rp.AimSeqNumber
and d.LearnRefNumber=rp.LearnRefNumber
and LearnDelFAMCode=rp.ApprenticeshipContractType
left join aecld
on
d.ukprn =aecld.ukprn
and d.aimseqnumber=aecld.AimSeqNumber
and d.LearnRefNumber=aecld.learnrefnumber
where LearnDelFAMType='ACT'
)
select
ukprn
,aimseqnumber
,LearnRefNumber
,LearnDelFAMCode
,LearnDelFAMType
,LearnDelFAMDateFrom
,LearningStartDate
,CASE
when rn=1 then LearnDelFAMDateFrom
when rn <1 then ''
when (rn =1 and rn > 1) and (LearningStartDate = LearnDelFAMDateFrom)
then LearnDelFAMDateFrom
else
''
end as LearnDelFAMDateFromMOD
,rn
,LearnDelFAMDateTo
FROM CTE_TEMP_TABLENAME