SELECT CASE WHEN avg(count)>12 THEN 5
WHEN avg(count)>8 THEN 4
WHEN avg(count)>2 THEN 3
WHEN avg(count)>1 THEN 2
ELSE 1
END,madeby
FROM (SELECT M.month,(SELECT count(*)
FROM Booking
WHERE date_trunc('month',starttime)=month
AND madeby=M.madeby
) AS count,M.madeby
FROM (SELECT date_trunc('month',generate_series(min(starttime),
current_timestamp,interval '1 month')::timestamp)
AS month,madeby
FROM Booking
GROUP BY madeby
) AS M
) AS BookingsPerMonth
GROUP BY madeby;
Now I need to do that computation there, I’m not questioning that. I’m guessing the problem is that it’s computing the aggregate function avg four times. The difference in times is from ~17 seconds with the CASE to ~4.5 seconds without (although I’m then lacking sufficient information)
Is there a way I can optimise this, through variable storage or something, such to bring the time closer to 4.5 seconds?
1 Answer