I have a table mydata in a Postgres 14 database, with the following relevant columns:
- ftype: an- enumhaving- foo,- barand- baz
- status: another- enumhaving- pending,- failed,- success
I want the success rate of different types. Success rate is basically: the number of rows where the status is success divided by total number of rows for that ftype.
Currently, I'm doing the following:
SELECT
    COALESCE(
        COUNT(CASE WHEN ftype = 'foo' AND status = 'success' THEN 1 END) / 
        NULLIF(COUNT(CASE WHEN ftype = 'foo' THEN 1 END)::real, 0)
    ,0)::real AS foo_rate,
    COALESCE(
        COUNT(CASE WHEN ftype = 'bar' AND status = 'success' THEN 1 END) / 
        NULLIF(COUNT(CASE WHEN ftype = 'bar' THEN 1 END)::real, 0)
    ,0)::real AS bar_rate,
    COALESCE(
        COUNT(CASE WHEN ftype = 'baz' AND status = 'success' THEN 1 END) / 
        NULLIF(COUNT(CASE WHEN ftype = 'baz' THEN 1 END)::real, 0)
    ,0)::real AS baz_rate,
FROM mydata;
Is there a better/more performant way? How can I optimize it?
Would using PARTITION in the query help?
 
    