create or replace view public.v_camp as
with female(used, fk_camp) as (
  select count(1), fk_camp
  from t_person
  where progress = 'approved'
  and sex = 'female'
  and camprole = 'student'
  group by fk_camp
), male(used, fk_camp) as (
  select count(1), fk_camp
  from t_person
  where progress = 'approved'
  and sex = 'male'
  and camprole = 'student'
  group by fk_camp
) select c.pk,
        (c.depart < now()) as is_over,
         c.name,
         c.arrive,
         c.depart,
         date_part('isoyear'::text, c.arrive) as year,
         l.name as location_name,
         c.min_age,
         c.max_age,
         coalesce(c.min_teacherage, c.max_age + 2) as min_teacherage,
         l.url,
         c.price,
         c.countries,
         c.fk_document,
         c.beds_female,
         c.beds_male,
         c.blocked_beds_female,
         c.blocked_beds_male,
         coalesce(male.used, 0) as used_beds_male,
         coalesce(female.used, 0) as used_beds_female,
         c.start_booking,
        (c.start_booking < now()) as booking_has_started
from public.t_camp c
left join public.t_location l on c.fk_location = l.pk
left join male on male.fk_camp = c.pk
left join female on female.fk_camp = c.pk;
