
            with curDT as (select cast(localtimestamp as TIMESTAMP WITH TIME ZONE) as curDate)
            select
                els.EvnLabSample_id as "EvnLabSample_id",
                ED.Lpu_sid as "Lpu_id",
                MS.MedService_Name as "MedService_Name",
                els.EvnLabSample_BarCode as "EvnLabSample_BarCode",
                MS.MedService_id as "MedService_id",
                MS.Lpu_id as "Lpu_id"
            from dbo.v_EvnLabSample els
                inner join v_EvnLabRequest elr on els.EvnLabRequest_id = elr.EvnLabRequest_id
                inner join lateral (
                    select msl.MedServiceLink_ExecutionRate
                    from v_MedServiceLink msl
                    where
                        msl.MedServiceLinkType_id = 1
                        and ((msl.MedService_lid = els.MedService_id and msl.MedService_id = elr.MedService_sid)
                        or (msl.MedService_id = els.MedService_id and msl.MedService_lid = elr.MedService_sid))
                    limit 1
                ) link on true
                -- PROMEDWEB-140549 Оптимизация
                inner join lateral (select ms.MedService_Name,
                                           ms.MedService_id,
                                           ms.Lpu_id
                                      from dbo.v_MedService ms
                                     where elr.MedService_id = ms.MedService_id
                                     limit 1) MS on true
                inner join lateral (select ed.Lpu_sid
                                      from dbo.v_EvnDirection_all ed
                                     where elr.EvnDirection_id = ed.EvnDirection_id
                                     limit 1) ed on true
            where
                els.EvnLabSample_setDT is not null
                and els.EvnLabSample_IsDeliveryPeriodMissed is null
                and els.EvnLabSample_DelivDT is null
                and elr.SampleStatusType_id = 4
                and (ELS.EvnLabSample_setDT >= ((select curDate from curDT) - interval '1 day' * 21)::date)
                and link.MedServiceLink_ExecutionRate is not null
                and (select curDate from curDT) >=
                     els.EvnLabSample_setDT + link.MedServiceLink_ExecutionRate::int * interval '1 minute'
            
