Untitled

                Never    
SQL
       
set search_path = _00000003, public;

explain (analyze, buffers)

with dept AS (
   WITH RECURSIVE sp AS (
      SELECT
         x."@Лицо" "Лицо",
         x."Раздел",
         x."Название",
         x."Раздел@",
         x."Тип"
      FROM "СтруктураПредприятия" x
      WHERE
         x."Флаги"[1] IS FALSE AND
         x."Тип" = ANY(ARRAY[0, 5]) AND
         x."@Лицо" = 14466736 -- Продвижение СБИС
      UNION ALL
      SELECT
         z."@Лицо" "Лицо",
         z."Раздел",
         z."Название",
         z."Раздел@",
         z."Тип"
      FROM "СтруктураПредприятия" z
           INNER JOIN sp y ON z."Раздел" = y."Лицо"
                          AND z."Тип" = y."Тип"
      WHERE
         z."Флаги"[1] IS FALSE AND
         z."$Черновик" IS NULL
   )
   SELECT
      "Лицо",
      "Раздел",
      "Название",
      "Раздел@"
   FROM sp
   
)
--select array_agg("Лицо") from dept

select *
from "Лид"
where
   "Список" = 147634153 -- 26K 
   and "Подразделение" = any(array[14466736,202,14466148,33711032,214,14463859,33311519,213,14466747,198,27164689,18089776,14430627,14466746,19103541,21603486,18301988,17990961,35296407,24958657,24723375,24723366,22706486,17990964,14467347,14467348,44261036,14430610,14430614,31996914])
   and "Черновик" IS NULL AND "Список" IS NOT NULL