59 lines
2.4 KiB
SQL
59 lines
2.4 KiB
SQL
with
|
|
deal_attributes as (
|
|
select
|
|
id_deal,
|
|
date_trunc('month', live_date_utc)::date as live_month,
|
|
date_trunc('month', cancellation_date_utc)::date as cancellation_month,
|
|
amount_of_properties,
|
|
case
|
|
when amount_of_properties between 1 and 5
|
|
then '01|05'
|
|
when amount_of_properties between 6 and 20
|
|
then '06|20'
|
|
when amount_of_properties between 21 and 60
|
|
then '21|60'
|
|
when amount_of_properties >= 61
|
|
then '61+'
|
|
else 'UNSET'
|
|
end as property_bucket
|
|
from {{ ref("int_hubspot__deal") }} ihd
|
|
-- Exclude deals without live dates
|
|
where live_date_utc is not null
|
|
),
|
|
monthly_revenue_per_property_bucket as (
|
|
select
|
|
date_trunc('month', m.date)::date as metric_month,
|
|
coalesce(d.property_bucket, 'global') as property_bucket,
|
|
count(*) as deals_active_in_month,
|
|
sum(coalesce(m.total_revenue_in_gbp, 0)) as total_revenue_in_gbp
|
|
from {{ ref("int_monthly_aggregated_metrics_history_by_deal") }} m
|
|
inner join
|
|
deal_attributes d
|
|
on m.id_deal = d.id_deal
|
|
and date_trunc('month', m.date) >= d.live_month
|
|
and date_trunc('month', m.date)
|
|
<= coalesce(d.cancellation_month, '2099-01-01')
|
|
and date_trunc('month', m.date)::date <> date_trunc('month', now())::date
|
|
where d.property_bucket <> 'UNSET'
|
|
group by rollup (date_trunc('month', m.date)::date, d.property_bucket)
|
|
having date_trunc('month', m.date)::date is not null
|
|
)
|
|
select
|
|
r.metric_month,
|
|
case
|
|
when r.metric_month + interval '12 months' >= date_trunc('month', now())::date
|
|
then 0
|
|
else 1
|
|
end as is_full_12_months_period,
|
|
r.property_bucket,
|
|
sum(coalesce(m.total_revenue_in_gbp, 0)) as cumulative_total_revenue_in_gbp,
|
|
sum(m.deals_active_in_month) as total_active_months,
|
|
sum(coalesce(m.total_revenue_in_gbp, 0))
|
|
/ sum(m.deals_active_in_month) as expected_mrr_per_month
|
|
from monthly_revenue_per_property_bucket m
|
|
inner join
|
|
monthly_revenue_per_property_bucket r
|
|
on r.metric_month > m.metric_month
|
|
and r.metric_month <= m.metric_month + interval '12 months'
|
|
and r.property_bucket = m.property_bucket
|
|
group by r.metric_month, is_full_12_months_period, r.property_bucket
|