
                
                
                SELECT 
            
            ccc.CmpCallCard_id as "CmpCallCard_id",
            ps.Person_id as "Person_id",
            ps.Server_id as "Server_id",
            ps.PersonEvn_id as "PersonEvn_id",
            ps.Person_SurName as "Person_SurName",
            ps.Person_FirName as "Person_FirName",
            ps.Person_SecName as "Person_SecName",
            to_char(ps.Person_BirthDay, 'DD.MM.YYYY') as "Person_Birthday",
            to_char(CmpCallCard_prmDT, 'DD.MM.YYYY')||' '||substring(to_char(CmpCallCard_prmDT, 'HH24:MI:SS'), 1, 5) as "CmpCallCard_prmDT",
            CmpReason_Name as "CmpReason_Name",
            coalesce(Lpu.Lpu_Nick, replace(replace(CmpLpu.CmpLpu_Name, '=', ''), '_+', ' ')) as "CmpLpu_Name",
            rtrim(udiag.Diag_Code)||' '||rtrim(udiag.Diag_Name) as "Diag_UName",
            rtrim(sdiag.Diag_Code)||' '||rtrim(sdiag.Diag_Name) as "Diag_SName",
            case when coalesce(CmpCallCard_IsPoli, 1) = 1 then 'false' else 'true' end as "CmpCallCard_IsPoli",
            to_char(CAST(vpl.EvnVizitPL_setDate as date), 'DD.MM.YYYY') as "EvnVizitPL_setDate",
            rtrim(vdiag.Diag_Code)||' '||rtrim(vdiag.Diag_Name) as "Diag_VName"
        
            
                FROM
                
            
            v_CmpCallCard ccc
            inner join v_PersonState ps on ps.Person_id = ccc.Person_id
            
            left join v_CmpReason cr on cr.CmpReason_id = ccc.CmpReason_id
            left join v_CmpLpu CmpLpu on CmpLpu.CmpLpu_id = ccc.CmpLpu_id
            left join v_Lpu Lpu on Lpu.Lpu_id = CmpLpu.Lpu_id
            left join v_Diag udiag on udiag.Diag_id = ccc.Diag_uid
            left join v_Diag sdiag on sdiag.Diag_id = ccc.Diag_sid
            
                left join lateral (
                    select
                        EvnVizitPL_setDate,
                        Diag_id
                    from v_EvnVizitPL vpl1
                    where vpl1.Person_id = ps.Person_id
                      and MedPersonal_id = '560101000032287'
                      and EvnVizitPL_setDate <= CmpCallCard_prmDT
                    order by EvnVizitPL_setDate desc
                    limit 1
                ) as vpl on true
            
            left join v_Diag vdiag on vdiag.Diag_id = CAST(vpl.Diag_id as bigint)
        
             
                
                        ORDER BY
                            
            
            ccc.Person_SurName,
            ccc.Person_FirName
        
            
                OFFSET 0 ROWS
                FETCH NEXT 100 ROWS ONLY
                
