with min_max as (
  select
    date_trunc('minute', min(start_stamp)) min_stamp
    ,date_trunc('minute', max(start_stamp)) max_stamp
  from
    xxx
  where
    start_stamp between '2014-08-01 00:00:00'::timestamp + %(min_stamp)s * interval '1 day' and '2014-08-01 23:55:00'::timestamp + %(min_stamp)s * interval '1 day'),
generated_interval as (
  select
    generate_series(min_stamp, max_stamp, interval '5 minutes') gs_stamp
  from
    min_max)
select
  gi.gs_stamp
  ,count(distinct c1.x1_id)
from
  generated_interval gi
left outer join
  calls c1
on
  c1.cstart_stamp < gi.gs_stamp + interval '5 minutes'
  and c1.cstart_stamp >= gi.gs_stamp
  and gi.gs_stamp between '2014-08-01 00:00:00'::timestamp + %(min_stamp)s * interval '1 day' and '2014-08-01 23:55:00'::timestamp + %(min_stamp)s * interval '1 day'
group by
  gi.gs_stamp
order by
  gi.gs_stamp;
