I want to make statistics on a table, and for this I use generate_series();
That's what I'm doing:
SELECT x.month, amount FROM (SELECT generate_series( min(date_trunc('month', date)), max(date_trunc('month', date)), '1 month' ) AS month FROM table WHERE user_id = 55 AND ... ) x LEFT JOIN ( SELECT SUM(amount) AS amount, date_trunc('month', date) AS month FROM table WHERE user_id = 55 AND ... GROUP BY month ) q ON q.month = x.month ORDER BY month
This works well, but when I want to apply filters, for example, to get the number for specific users, I have to apply them twice. Is there a way to avoid filtering twice, or rewrite it in a more efficient way, because I'm not sure if this is the right thing to do?
source share