Hi @Bone_12 ,
Please have a try with below:
;with cte as (
select
distinct
a.mort_no,
case when isnumeric(substring(a.cust_no,5,6)) = 1 then substring(a.cust_no,5,6) else null end as cust_no,
c.start_date,
substring(a.comp_id,3,6) as comp_id,
b.userid,
case percentage_allocation when 0 then sum(c.val) over (partition by a.mort_no , c.start_date, e.percentage_allocation, e.label )
else
sum(c.val) over (partition by a.mort_no , c.start_date, e.percentage_allocation, e.label ) * (e.percentage_allocation / 100) end as compvalue,
e.percentage_allocation,
e.label,
'mp' as system
from [mo_db].[dbo].[mo_table] as a
left join [mo_db].[dbo].[id_table] as b
on a.[userid] = b.[userid]
left join [mo_db].[dbo].[jt_table] as c
on a.mort_no = c.mort_no
left join [mo_db].[dbo].[lookup] as e
on substring(a.cust_no,5,6) = substring(e.cust_no,5,6)
where e.label in ('aaa','aab','a'))
select * from cte
except
select * from cte
where mort_no in (select mort_no from [mo_table] where percentage_allocation<>0) and percentage_allocation=0
If above is not working, we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data.
Best regards,
Melissa
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.