CREATE OR REPLACE FUNCTION sp_getnewscount("UserID" uuid, "Groups" varchar = null) RETURNS SETOF text
    LANGUAGE plpgsql
    AS $_$
Declare UserIDVar Alias for "UserID";
    GroupsVar Alias for "Groups";
Begin
    Return Query
    select sum(c1)::text || '(' || sum(c2)::text || ')'
    from (
        select 
            1 as c1,
            case
                when not exists(
                    select *
                    from VCLib.T_NEWS_BOX_LINK_USERS nblu
                    where nb.NewsBoxID = nblu.NewsBox
                            and
                        nblu.Users = UserIDVar
                ) then 1
                else 0
            end as c2
        from VCLib.T_NEWS_BOX nb
        where nb.NewsBoxID in (
            select nblm.NewsBox
            from VCLib.T_NEWS_BOX_LINK_MODULE nblm
            where exists(
                select *
                from VCLib.T_ROLE_CLIENT_MODULES rcm
                where rcm.ClientModuleID = nblm.ClientModules
                        and
                    exists(
                        select *
                        from VCLib.T_USERS_ROLES ur
                        where ur.UserID = UserIDVar
                    )
            )
            union all
            select nblr.NewsBox
            from VCLib.T_NEWS_BOX_LINK_ROLES nblr
            where exists(
                select *
                from VCLib.T_USERS_ROLES ur
                where ur.UserID = UserIDVar
            )
            union all
            select nbug.NewsBox
            from VCLib.T_NEWS_BOX_USERS_GROUP nbug
                join fn_Split(GroupsVar, ';') g on g.Split::uuid = nbug.UsersGroup
            where GroupsVar is not null
        )
    ) t;
End;
$_$;
