To me this looks like a botched attempt in sub-typing. This is what I think you have now.
Based on the model, the following should work:
;
with
q_00 as (
select
pa.Deal_Id as Deal_Id
, coalesce(sp.BROJ_TIKETA, fw.BROJ_TIKETA, sw.tiket, ia.BROJ_TIKETA, '') as Ticket_No
, coalesce(sp.Trans_Id, fw.Trans_Id, sw.Trans_Id, ia.Trans_Id) as Trans_Id
from #PotencijalniAktuelni as pa
left join kplus_sp as sp on sp.sp_Id = pa.Deal_Id and pa.KplusTable_Id = 1
left join kplus_fw as fw on fw.fw_Id = pa.Deal_Id and pa.KplusTable_Id = 2
left join dev_sw as sw on sw.sw_Id = pa.Deal_Id and pa.KplusTable_Id = 3
left join kplus_ia as ia on ia.ia_Id = pa.Deal_Id and pa.KplusTable_Id = 4
)
select
Deal_Id
, max(Trans_Id) as TransId_CurrentMax
into #MaxRazlicitOdNull
from q_00
where Ticket_No <> ''
group by Deal_Id ;
SQL Server 2005 +
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…