In my app an area
can have many happenings
. I want to find out over a given timespan, what percentage of those weeks had at least one session listed. It doesn't matter how many were listed, so long as there was at least one. So as an example, say in February Area X listed 5 sessions in week 1, 0 in week 2, 1 in week 3, 1 in week 4 then I should get back that Area X has a listing rate of 75% (3 out of 4 weeks had at least one session)
I've tried to accomplish this using the following query:
SELECT a.location, sum(case when date_trunc('week', h.started_at) is null then 0 else 1 end) / (({{end}} - {{start}}) / 7)::float * 100 as percentage
FROM areas a
JOIN happenings h on h.primary_area_id = a.id
and h.started_at between {{start}} and {{end}}
group by 1
My thinking is that go through each week, if a happening exists then give it a value of 1, if not 0. Then divide that by the number of weeks and multiply by 100 to get the percentage.
But the fact that I'm getting percentages over 100% indicates to me that weeks with multiple happenings are being counted for more than 1. What's the best way to limit it to 0 or 1 for a given week? Is there a better way to calculate this?