
    with curDT as (select localtimestamp as curDate)
    select count(*) as cnt from (    -- TOP SL, FIXDATE 07.03.2023, JIRA PROMEDWEB-140236
    
    SELECT
        S.SMI_id
    FROM
        -- from
        vimis.v_SMI S
        inner join vimis.VimisType VT on vt.VimisType_id = s.VimisType_id
        INNER JOIN LATERAL (
            select
                SMIVersion_id,
                SMIVersionStatus_id
            from
                vimis.v_SMIVersion
            where
                SMI_id = S.SMI_id
            order by
                SMIVersion_id desc
            LIMIT 1
        ) SV ON TRUE
        inner join vimis.v_VimisTriggerSMI VTS ON SV.SMIVersion_id = VTS.SMIVersion_id
        inner join vimis.v_VimisTrigger VTg on VTS.VimisTrigger_id = VTg.VimisTrigger_id
        inner join vimis.v_VimisTriggerType VTT ON VTT.VimisTriggerType_id = VTg.VimisTriggerType_id
            
        inner join vimis.v_SMITypeLocal STL on STL.SMITypeLocal_id = S.SMITypeLocal_id
        inner join vimis.v_SMIType ST on STL.SMIType_id = ST.SMIType_id 
        inner join vimis.v_SMIVersionStatus SVS on SV.SMIVersionStatus_id = SVS.SMIVersionStatus_id
            
        inner join dbo.v_PersonState PS ON S.Person_id = PS.Person_id
        inner join v_Lpu_lite Lpu on Lpu.Lpu_id = s.Lpu_id
        -- Фильтруем СМС-ки только для активных вимисов, т.к. в базе появились СМС для сторонних сервисов.
        left join dbo.v_LpuBuilding LB ON S.LpuBuilding_id = LB.LpuBuilding_id
        left join lateral (
            select
                msfc.MedStaffFact_id,
                msfc.Person_Fin,
                msfc.Person_Fio,
                msfc.lpu_id
            from
                v_MedStaffFact msfc
            where
                msfc.MedPersonal_id = s.MedPersonal_id and
                msfc.Lpu_id = s.Lpu_id and
                msfc.WorkData_begDate < s.SMI_SMIDate
            order by
                MedStaffFact_id
                offset 0 rows fetch next 1 rows only
        ) mp on true

        left join vimis.v_VimisJournalQuery VJQ ON (VTS.VimisTriggerSMI_id = VJQ.VimisTriggerSMI_id)
        LEFT JOIN LATERAL (
            select
                count(E.VimisQueryError_id) as CNT
            from
                vimis.v_VimisQueryError E
            where
                E.VimisJournalQuery_id = VJQ.VimisJournalQuery_id
        ) t ON TRUE
        -- end from
    WHERE
        -- where
        (1=1)
         and ((S.SMI_SMIDate >= CAST('2023-01-19' as date) and S.SMI_SMIDate < CAST('2023-07-20' as date)) and
        (VJQ.VimisJournalQuery_OutDT >= CAST('2023-07-19' as date) and VJQ.VimisJournalQuery_OutDT < CAST('2023-07-20' as date)) and
        S.VimisType_id in (1,4,3,2))
        -- end where
     order by S.SMI_id 
 offset 0 rows fetch next 10000 rows only ) as query
