Skip to content

Instantly share code, notes, and snippets.

@jorpic
Last active February 5, 2016 19:42
Show Gist options
  • Save jorpic/0b0717e470efe4ab670a to your computer and use it in GitHub Desktop.
Save jorpic/0b0717e470efe4ab670a to your computer and use it in GitHub Desktop.
Query that will benefit from grouping sets
with
events as
(select
modelid as ctr,
ctime,
(patch->>'isActive')::bool as isActive
from "Event"
where modelname = 'Contract'
and type = 'Update'
and (patch->>'isActive')::bool is not null
),
extra_events as
(select distinct on (ctr)
ctr,
current_timestamp,
not isActive
from events
order by ctr, ctime desc
),
active_periods as
(select distinct
ctr,
coalesce(
lag(e.ctime) over (partition by ctr order by e.ctime), -- max(ctime, from)
c.ctime) :: date as active_from,
e.ctime :: date as active_till
from (select * from events union select * from extra_events) e
join "Contract" c on (c.id = e.ctr)
where not e.isActive
),
filtered_periods as
(select
ctr,
daterange(active_from, active_till) * '[2015-01-01,2016-01-01]' as active_range
from active_periods
where
daterange(active_from, active_till) && '[2015-01-01,2016-01-01]'
)
select *
from
(select
p.ctr,
c.vin,
make.label,
model.label,
c.plateNum,
null as active_from,
null as active_till,
p.total
from (
select ctr, sum(upper(active_range) - lower(active_range)) as total
from filtered_periods
group by ctr) p
join "Contract" c on (p.ctr = c.id)
left join "CarMake" make on (c.make = make.id)
left join "CarModel" model on (c.model = model.id)
) x
union
(select
ctr, null, null, null, null,
lower(active_range), upper(active_range),
upper(active_range) - lower(active_range)
from filtered_periods
)
order by ctr, active_from nulls first;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment