
                
                
                SELECT 
                M.Message_id as "Message_id",
                M.Message_pid as "Message_pid",
                to_char(cast(M.Message_setDT as timestamp), 'DD.MM.YYYY HH24:MI:SS') as "Message_setDT",
                M.UserSend_ID as "UserSend_ID",
                M.Message_Subject as "Message_Subject",
                COALESCE(M.Message_Text, '') as "Message_Text",

                
                    MR.Message_isRead as "Message_isRead",
                    MR.MessageRecipient_id as "MessageRecipient_id",
                    MR.UserRecipient_id as "UserRecipient_id",
                    MR.Message_isFlag as "Message_isFlag",
                
                M.NoticeType_id as "NoticeType_id",
                case when M.UserSend_ID = 0 then 'PromedWeb' else RTRIM(PUC.PMUser_Login) end as "PMUser_Login",
                PUC.PMUser_id as "PMUser_id",
                LPU.Lpu_Nick as "Lpu_Nick",
                MP.Dolgnost_Name as "Dolgnost_Name",
                case when M.UserSend_ID = 0 then 'Система' else
                    RTRIM((case when (PUC.PMUser_surName is not null) then RTRIM(PUC.PMUser_surName) || ' ' else '' end) ||
                        (case when (PUC.PMUser_firName is not null) then SUBSTRING(RTRIM(PUC.PMUser_firName),1,1) || '. ' else '' end) ||
                        (case when (PUC.PMUser_secName is not null) then SUBSTRING(RTRIM(PUC.PMUser_secName),1,1) || '.' else '' end)
                    ) end as "PMUser_Name"
                
                FROM
                
                msg.v_Message M

                --left join msg.v_NoticeType NT  on NT.NoticeType_id = M.NoticeType_id

                left join msg.v_MessageRecipient MR  on MR.Message_id = M.Message_id
                left join pmUserCache PUC  on PUC.PMUser_id = M.UserSend_ID

                left join v_Lpu_all LPU  on LPU.Lpu_id = PUC.Lpu_id

                left join v_MedPersonal MP  on MP.MedPersonal_id = PUC.MedPersonal_id

                    and PUC.Lpu_id = MP.Lpu_id
                 WHERE 
                1=1 and MR.UserRecipient_id = '370716441502' and M.Message_isSent is not null
                
                
                        ORDER BY
                            
                MR.Message_isRead desc,
                M.Message_setDT desc
                
                OFFSET 0 ROWS
                FETCH NEXT 100 ROWS ONLY
                
