Ваше требование немного трудно понять для меня. Но для первой части вашей проблемы я думаю, что могу ответить:
Исходная ситуация
У вас есть таблица 'application (id int primary key, метка времени создания_даты)'
Что вам нужно (для моего понимания)
Номер заявки на триместр (с января по март и т. Д.)
Возможное решение
select a.delta, sum(applicationByMonth) as applicationByMonth, sum(leadByMonth) as leadByMonth
from
(
select '1 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as applicationByMonth
from applications
where cast(date_part('month', creation_date) as int) <= 3
group by cast(date_part('month', creation_date) as int)
union
select '2 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as applicationByMonth
from applications
where cast(date_part('month', creation_date) as int) between 4 and 6
group by cast(date_part('month', creation_date) as int)
union
select '3 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as applicationByMonth
from applications
where cast(date_part('month', creation_date) as int) between 7 and 9
group by cast(date_part('month', creation_date) as int)
union
select '4 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as applicationByMonth
from applications
where cast(date_part('month', creation_date) as int) between 10 and 12
group by cast(date_part('month', creation_date) as int)
) as a
inner join
(
select '1 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as leadByMonth
from m_lead
where cast(date_part('month', creation_date) as int) <= 3
group by cast(date_part('month', creation_date) as int)
union
select '2 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as leadByMonth
from m_lead
where cast(date_part('month', creation_date) as int) between 4 and 6
group by cast(date_part('month', creation_date) as int)
union
select '3 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as leadByMonth
from m_lead
where cast(date_part('month', creation_date) as int) between 7 and 9
group by cast(date_part('month', creation_date) as int)
union
select '4 trimester' as delta, cast(date_part('month', creation_date) as int) as month, count(id) as leadByMonth
from m_lead
where cast(date_part('month', creation_date) as int) between 10 and 12
group by cast(date_part('month', creation_date) as int)
) as l
on a.delta = l.delta
group by a.delta
order by 1;
Я думаю, что вы можете адаптироваться к вашим потребностям.
Надеюсь, это поможет;)