;with base as (
select a.*,row_number() over (partition by (personid) order by mydate desc) as rn
,case when a.a is not null then 'A'
when a.b is not null then 'B'
else 'C' end as Type
from mytable as a
)
select a.personid,a.type
,case a.type when 'A'
then case when b.minb < b.minc then b.minb -1
when b.minc < b.minb then b.minC -1
when b.minb is not null and b.minc is null then b.minb - 1
when b.minb is null and b.minc is not null then b.minc -1
else b.maxa end
when 'B'
then case when b.mina < b.minc then b.mina -1
when b.minc < b.mina then b.minC -1
when b.mina is not null and b.minc is null then b.mina - 1
when b.mina is null and b.minc is not null then b.minc -1
else b.maxb end
else
case when b.minb < b.mina then b.minb -1
when b.mina < b.minb then b.mina -1
when b.minb is not null and b.mina is null then b.minb - 1
when b.minb is null and b.mina is not null then b.mina -1
else b.maxc end
end as conseccount
from (select personid,type from base where rn=1) as a
inner join (select personid
,min(case type when 'A' then rn else null end) as minA
,min(case type when 'B' then rn else null end) as minb
,min(case type when 'C' then rn else null end) as minc
,max(case type when 'A' then rn else null end) as maxA
,max(case type when 'B' then rn else null end) as maxb
,max(case type when 'C' then rn else null end) as maxc
from base
group by personid
)as b
on a.personid=b.personid
order by 1
|