
            with lr as (
                select
                    EvnDirection_id,
                    EvnStatus_id,
                    EvnLabRequest_id,
                    EvnLabRequest_PrmTime,
                    EvnLabRequest_StatusDate
                from v_EvnLabRequest lr
                where (
                    lr.EvnLabRequest_StatusDate::date  between '2023-01-07' and '2023-07-20'
                    or lr.EvnLabRequest_PrmTime::date  between '2023-01-07' and '2023-07-20'
                )
                and (lr.MedService_id = '15757')

                
                union
                select
                    EvnDirection_id,
                    EvnStatus_id,
                    EvnLabRequest_id,
                    EvnLabRequest_PrmTime,
                    EvnLabRequest_StatusDate
                from v_EvnLabRequest lr
                where (1=1)
                    and (
                        lr.EvnLabRequest_StatusDate::date  between '2023-01-07' and '2023-07-20'
                        or lr.EvnLabRequest_PrmTime::date  between '2023-01-07' and '2023-07-20'
                    )
                    
                    and lr.MedService_id in ('15757','500801000000059','500801000000060','500801000001801','500801000001845','500801000001850','500801000003483')
                
                    and exists (
                        select 1 ex
                        from v_EvnLabSample els
                        where els.EvnLabRequest_id = lr.EvnLabRequest_id
                            and els.MedService_id = '15757'
                        limit 1
                    )
            
            )
            select
                A.EvnStatus_id as "EvnStatus_id",
                count(A.EvnDirection_id) as "count"
            from (
                select distinct
                    lr.EvnDirection_id as EvnDirection_id,
                    lr.EvnStatus_id as EvnStatus_id
                from lr
                    inner join v_EvnDirection_all ed on lr.EvnDirection_id = ed.EvnDirection_id
                    
                where (1=1)
                    and ((lr.EvnStatus_id = 1 and (
                          (lr.EvnLabRequest_PrmTime is null and lr.EvnLabRequest_StatusDate::date  between '2023-01-07' and '2023-07-20') or
                          lr.EvnLabRequest_PrmTime::date  between '2023-01-07' and '2023-07-20'))
                          or (lr.EvnStatus_id > 1 and lr.EvnLabRequest_StatusDate::date  between '2023-01-07' and '2023-07-20'))
                    and ed.dirtype_id in (10, 25, 30)
                    and ed.DirFailType_id is null
                    and (lr.EvnStatus_id IN (3,4) OR COALESCE(ED.EvnStatus_id, 1) not in (12,13))
                    
            ) A
            
            group by A.EvnStatus_id
        
