Объединение нескольких подзапросов
Всем привет! Есть два запроса, которые нужно объединить, чтобы на выходе получился следующий результат:
1 запрос
with
oems as (
select unnest(array['54830D7000']) oem
)
select k.pv, sum(count) as istcohnik1 from (
select p.value->>'raw' as pv, count(distinct contractor_code)
from stat.phrase p
join oems o on o.oem=p.value->>'raw'
join stat.event_request_stat rq on rq.phrase_uid=p.uid and lower(rq.period) between '9999-99-99' and '9999-99-99' and rq.period_type='M'
where p.value->>'raw' is not null and contractor_code is not null and src in ('источник1')
group by p.value->>'raw') as K
group by k.pv
2 запрос:
select t.pv, sum(count) as istcohnik2 from (
select p1.value->>'raw' as pv1, count(distinct contractor_code)
from stat.phrase p1
join oems o on o.oem=p1.value->>'raw'
join stat.event_request_stat rq on rq.phrase_uid=p1.uid and lower(rq.period) between '9999-99-99' and '9999-99-99' and rq.period_type='M'
where p1.value->>'raw' is not null and contractor_code is not null and src in ('Источник2')
group by p1.value->>'raw') as T
group by t.pv
Сначала пытался объединить через рекурсивные запросы, но это было не то. Наиболее логичным кажется объединение через join и подзапросы.
with
oems as (
select unnest(array['54830D7000']) oem
)
select k.pv, istochnik2, istochnik1 from (
select p.value->>'raw' as pv, count(distinct contractor_code) as istochnik2
from stat.phrase p
join oems o on o.oem=p.value->>'raw'
join stat.event_request_stat rq on rq.phrase_uid=p.uid and lower(rq.period) between '9999-99-99' and '9999-99-99' and rq.period_type='M'
where p.value->>'raw' is not null and contractor_code is not null and src in ('источник1', 'источник2')
group by p.value->>'raw', contractor_code) as K
join (select pv, sum(count) as istochnik1 from (
select p1.value->>'raw' as pv1, count(distinct contractor_code)
from stat.phrase p1
join oems o on o.oem=p1.value->>'raw'
join stat.event_request_stat rq on rq.phrase_uid=p1.uid and lower(rq.period) between '9999-99-99' and '9999-99-99' and rq.period_type='M'
where p1.value->>'raw' is not null and contractor_code is not null and src in ('источник1')
group by p1.value->>'raw', contractor_code) as T on k.pv=t.pv
В данном случае, CTE подходит больше, чем where in, так как позволяет повысить производительность и снизить время вычисления.
