On Sat, Oct 17, 2020 at 8:00 AM Martin Norbäck Olivers <martin(at)norpan(dot)org>
wrote:
> I'm looking at all the aggregation functions but can't quite find one that
> suits this purpose.
>
> I would love to get some input on ways to make this faster.
>
If you want counts the count function is your goto aggregate function.
What you are missing is performing conditional counting.
SELECT fld, count(*) FILTER (WHERE expression) FROM query GROUP BY fld;
https://www.postgresql.org/docs/13/sql-expressions.html#SYNTAX-AGGREGATES
David J.