select * from
(
with
  status(status, status_id, probability_pc) as
     (
             VALUES 
               ('Закрыта неуспешно',7,0) ,
               ('Закрыта успешно',6,100)        ,
               ('Договор подписан',5,100)       ,
               ('Договор на подписании',15,90)  ,
               ('Договор на согласовании',12,70),
               ('Тестирование',8,50)            ,
               ('Отправлено ТКП',10,20)         ,
               ('Внутреннее согласование',37,10),
               ('Проработка решения',4,10)      ,
               ('Сбор потребностей',1,0) 
     ),
     line as 
     (
             SELECT
                     siv.__id             as siv_uid               ,
                     siv.discount                                  ,
                     siv.type             as line_pricing_model_id ,
                     siv.hash             as line_key              ,
                     siv.is_actual        as siv_is_actual         ,
                     siv.version::numeric as line_version          ,
                     d.__index            as deal_index            ,
                     d._companies                                  ,
                     a.index              as agreement_version     ,
                     siv.date_nop::date   as dt_from               ,
                     siv.date_end::date   as dt_to                 ,
                     siv.is_easy          as is_simple             ,
                     siv.cnt                      ,
                     s.probability_pc                              ,
                     a.__id               as agreement_uid         ,
                     a.contract_uid                                ,
                     a.is_actual          as agreement_is_actual   ,
                     a.deal_uid                                    ,
                     d.__name             as deal                  ,
                     d.__status_status    as deal_status_id        ,
                     siv.user_description                          ,
                     siv.params
             FROM
                     elma.deals_services siv
                  JOIN elma.deals d on (d.__id = ANY(siv.deal))
                  JOIN status s on (d.__status_status=s.status_id)
                  LEFT JOIN elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement))
             WHERE
                     siv.is_actual
                 AND siv."__deletedAt" IS NULL
                 and d."__deletedAt" IS NULL
                 and a."__deletedAt" IS NULL
                 and a.is_actual
                 and siv.type IN (2,3) 
   ),
     component as
     (
             SELECT
                     price*cnt*(100.0-COALESCE(discount,0))/100.0 as cost ,
                     price                                                ,
                     cnt                                                  ,
                     code                                                 ,
                     __id
             FROM
                     elma.service_parametrs
             where
                     "__deletedAt" IS NULL 
     ),
     stair as
     (
             select
                     *
             FROM
                     (
                             SELECT
                                     *,
                                     MIN(dt_from) OVER (PARTITION BY line_key ORDER BY deal_index desc) running_min_dt
                             FROM
                                     line
                             WHERE
                                     probability_pc > 0 
                       ) t
             WHERE
                     t.dt_from = t.running_min_dt
             AND     t.dt_to   > CURRENT_TIMESTAMP
             OR      t.dt_to IS NULL 
     ),
     alloc as
     (
             select
                     c."WZ"                           as wz     ,
                     round(sum(c."VM_RAM_Allocated")) as ram    ,
round(sum(CASE WHEN "VM_is_ON" > 0 THEN c."VM_RAM_Allocated" ELSE 0 END)) as ram_on ,
                     round(sum(c."VM_vCPU_count"))    as cpu    ,
                     round(sum(CASE WHEN "VM_is_ON" > 0 then c."VM_vCPU_count" ELSE 0 END))                    as cpu_on
             from
                     vmreports.compute c
             where
                     ts= (select max(ts) from vmreports.compute)
           group by c."WZ" 
   ),
     disk_alloc as
     (
             select
                     c."WZ"                         as wz ,
                     round(sum(c."Disk_Allocated")) as disk_alloc
             from
                     vmreports.storage c
             where
                     ts= (select max(ts) from vmreports.compute)
             group by
                     c."WZ" 
     ),
     sold_ram as
     (
             SELECT
                     z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes                     
             FROM
                     stair o
                  JOIN elma.companies z on (o._companies=z.__id)
                  LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
                     c.code SIMILAR TO 'iaas.(ngc|dcp).%.ram-_'
                  AND     c.cnt <> 0
                  AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     sold_cpu as
     (
             SELECT
                     z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes                     
             FROM
                     stair o
             JOIN
                     elma.companies z on (o._companies=z.__id)
                  LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
                     c.code SIMILAR TO 'iaas.(ngc|dcp).%.vcpu%-_'
                 AND     c.cnt <> 0
                 AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     sold_disk as
     (
             SELECT
                     z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes
             FROM
                     stair o
                  JOIN elma.companies z on (o._companies=z.__id)
                  LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
                     c.code SIMILAR TO 'iaas.(ngc|dcp).%.(ssd|fstssd|sata)-_'
                 AND     c.cnt <> 0
                 AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     deal_stat as
     (
             select
                     STRING_AGG(distinct deal_status_id::text,', ' order by deal_status_id::text)        as status_ids             ,
                     STRING_AGG(distinct line_pricing_model_id::text,', ' order by line_pricing_model_id::text) as line_pricing_model_ids ,
                     z.id_klienta                                          as WZ
             from
                     line o
                  join elma.companies z on (o._companies=z.__id)
             GROUP BY
 z.id_klienta 
   )
select
        r.wz       as wz_sold      ,
        r.client   as client_sold  ,
        r.company_uid              ,
        a.wz       as wz_alloc     ,
        ds.status_ids              ,
        ds.line_pricing_model_ids  ,
        r.codes    as ram_codes    ,
        r.quantity as ram_sold     ,
        a.ram      as ram_alloc    ,
        a.ram_on   as ram_alloc_on ,
        c.codes    as cpu_codes    ,
        c.quantity as cpu_sold     ,
        a.cpu      as cpu_alloc    ,
        a.cpu_on   as cpu_alloc_on ,
        d.codes    as disk_codes   ,
        d.quantity as disk_sold    ,
        da.disk_alloc              ,
        z.__name   as alloc_company,
        z.__id     as alloc_company_uid
from
        sold_ram r
    join deal_stat ds on (lower(r.wz)=lower(ds.wz))
    join sold_cpu c on (lower(r.wz)=lower(c.wz))
    left join sold_disk d on (lower(r.wz)=lower(d.wz))
    full join alloc a on (lower(r.wz)=lower(a.wz))
    left join disk_alloc da on (a.wz=da.wz)
    left join elma.companies z on (lower(a.wz)=lower(z.id_klienta))
)
    
intersect all  

select * from 
(
WITH 
   status(status, status_id, probability_pc) as
     (
             VALUES 
               ('Закрыта неуспешно',7,0) ,
               ('Закрыта успешно',6,100)       ,
               ('Договор подписан',5,100)       ,
               ('Договор на подписании',15,90)  ,
               ('Договор на согласовании',12,70),
               ('Тестирование',8,50)            ,
               ('Отправлено ТКП',10,20)         ,
               ('Внутреннее согласование',37,10),
               ('Проработка решения',4,10)      ,
               ('Сбор потребностей',1,0) 
     ),
     line_expanded as 
     (
             SELECT
                     siv.__id             as siv_uid               ,
                     siv.discount                                  ,
                     siv.type             as line_pricing_model_id ,
                     siv.hash             as line_key              ,
                     siv.is_actual        as siv_is_actual         ,
                     siv.version::numeric as line_version          ,
                     d.__index            as deal_index            ,
                     d._companies                                  ,
                     a.index              as agreement_version     ,
                     siv.date_nop::date   as dt_from               ,
                     siv.date_end::date   as dt_to                 ,
                     siv.is_easy          as is_simple             ,
                     siv.cnt                     ,
                     s.probability_pc                              ,
                     a.__id               as agreement_uid         ,
                     a.contract_uid                                ,
                     a.is_actual          as agreement_is_actual   ,
                     a.deal_uid                                    ,
                     d.__name             as deal                  ,
                     d.__status_status    as deal_status_id       ,
                     siv.user_description                          ,
                     unnest(siv.params) as param_id
             FROM
                     elma.deals_services siv
                  JOIN elma.deals d on (d.__id = ANY(siv.deal))
                  JOIN status s on (d.__status_status=s.status_id)
                  LEFT JOIN elma.additional_agreements a on (a.__id = ANY(siv.additional_agreement))
             WHERE
                     siv.is_actual
                 AND siv."__deletedAt" IS NULL
                 and d."__deletedAt" IS NULL
                 and a."__deletedAt" IS NULL
                 and a.is_actual
                 and siv.type IN (2,3) 
   ),
     component as
     (
             SELECT
                     price*cnt*(100.0-COALESCE(discount,0))/100.0 as cost ,
                     price                                                ,
                     cnt                                                  ,
 code                                                 ,
                     __id
             FROM
                     elma.service_parametrs
             where
                     "__deletedAt" IS NULL 
     ),
     stair as
     (
             select
                     *
             FROM
                     (
                             SELECT
                                     *,
                                     MIN(dt_from) OVER (PARTITION BY line_key ORDER BY deal_index desc) running_min_dt
                             FROM
                                    line_expanded
                                 --line
                             WHERE
                                     probability_pc > 0 
                       ) t
             WHERE
                     t.dt_from = t.running_min_dt
             AND     t.dt_to   > CURRENT_TIMESTAMP
             OR      t.dt_to IS NULL 
     ),
     alloc as
     (
             select
                     c."WZ"                           as wz     ,
                     round(sum(c."VM_RAM_Allocated")) as ram    ,
                     round(sum(CASE WHEN "VM_is_ON" > 0 THEN c."VM_RAM_Allocated" ELSE 0 END)) as ram_on ,
                     round(sum(c."VM_vCPU_count"))    as cpu    ,
                     round(sum(CASE WHEN "VM_is_ON" > 0 then c."VM_vCPU_count" ELSE 0 END))                    as cpu_on
             from
                     vmreports.compute c
             where
                     ts= (select max(ts) from vmreports.compute)
           group by c."WZ" 
   ),
     disk_alloc as
     (
             select
                     c."WZ"                         as wz ,
                     round(sum(c."Disk_Allocated")) as disk_alloc
             from
                     vmreports.storage c
             where
                     ts= (select max(ts) from vmreports.compute)
             group by
                     c."WZ" ),
     sold_ram as
     (
             SELECT
                     z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes
             FROM
                     stair o
                  JOIN elma.companies z on o._companies=z.__id
                  LEFT JOIN component c on c.__id = o.param_id
                  --LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
           --c.code SIMILAR TO 'iaas.(ngc|dcp).%.ram-_'
                  (c.code LIKE 'iaas.ngc.%.ram-_' OR c.code LIKE 'iaas.dcp.%.ram-_')
                  AND     c.cnt <> 0
                  AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     sold_cpu as
     (
             SELECT
                     z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes                     
             FROM
                     stair o
             JOIN
                     elma.companies z on (o._companies=z.__id)
                  LEFT JOIN component c on c.__id = o.param_id
                     --LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
                     --c.code SIMILAR TO 'iaas.(ngc|dcp).%.vcpu%-_'
                     (c.code LIKE 'iaas.ngc.%.vcpu%-_' OR c.code LIKE 'iaas.dcp.%.vcpu%-_')
                 AND     c.cnt <> 0
                 AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     sold_disk as
     (
             SELECT
 z.id_klienta            as WZ         ,
                     z.__name                as client     ,
                     z.__id                  as company_uid,
                     round(sum(c.cnt*o.cnt)) as quantity   ,
                     count(*)                as lines      ,
                     STRING_AGG(c.code,', ' order by c.code) as codes
             FROM
                     stair o
                  JOIN elma.companies z on (o._companies=z.__id)
                  LEFT JOIN component c on c.__id = o.param_id
                  --LEFT JOIN component c on (c.__id = ANY (o.params))
             WHERE
                     --c.code SIMILAR TO 'iaas.(ngc|dcp).%.(ssd|fstssd|sata)-_'
                     (c.code LIKE 'iaas.ngc.%.ssd-_' OR c.code LIKE 'iaas.dcp.%.ssd-_'
                       or c.code LIKE 'iaas.ngc.%.fstssd-_' OR c.code LIKE 'iaas.dcp.%.fstssd-_'
                       or c.code LIKE 'iaas.ngc.%.sata-_' OR c.code LIKE 'iaas.dcp.%.sata-_'
                     )
                 AND     c.cnt <> 0
                 AND     o.cnt <> 0
             GROUP BY
                     z.id_klienta,
                     z.__id      ,
                     z.__name 
   ),
     deal_stat as
     (
             select
                     STRING_AGG(distinct deal_status_id::text,', ' order by deal_status_id::text)        as status_ids             ,
                     STRING_AGG(distinct line_pricing_model_id::text,', ' order by line_pricing_model_id::text) as line_pricing_model_ids ,
                     z.id_klienta                                          as WZ
             from
                     line_expanded o
                  --line o
                  join elma.companies z on (o._companies=z.__id)
             GROUP BY
                     z.id_klienta 
   )
select
        r.wz       as wz_sold      ,
        r.client   as client_sold  ,
        r.company_uid              ,
        a.wz       as wz_alloc     ,
        ds.status_ids              ,
        ds.line_pricing_model_ids  ,
        r.codes    as ram_codes    ,
        r.quantity as ram_sold     ,
        a.ram      as ram_alloc    ,
        a.ram_on   as ram_alloc_on ,
        c.codes    as cpu_codes    ,
        c.quantity as cpu_sold     ,
        a.cpu      as cpu_alloc    ,
        a.cpu_on   as cpu_alloc_on ,
        d.codes    as disk_codes   ,
        d.quantity as disk_sold    ,
        da.disk_alloc              ,
        z.__name   as alloc_company,
        z.__id     as alloc_company_uid
from
        sold_ram r        
    join deal_stat ds on (lower(r.wz)=lower(ds.wz))
        join sold_cpu c on (lower(r.wz)=lower(c.wz))
    left join sold_disk d on (lower(r.wz)=lower(d.wz))
    full join alloc a on (lower(r.wz)=lower(a.wz))
    left join disk_alloc da on (a.wz=da.wz)
    left join elma.companies z on (lower(a.wz)=lower(z.id_klienta))
)