1

Lets say I have a postgres table with the following data:

hostname | status
---------+--------
a1       | C
a1       | C
a1       | NC
a2       | NC
a2       | NC
a2       | C

I want to display the count of status for C and NC for each hostname, like this:

hostname | C total| NC total | Total (C+NC) | C %
---------+--------+----------+--------------+-----
a1       | 2      | 1        | 3            |66.66
a2       | 1      | 2        | 3            |33.33

1 Answer 1

1

You can use conditional aggregation:

select hostname,
       count(*) filter (where status = 'C') as num_c,
       count(*) filter (where status = 'NC') as num_nc
from t
group by hostname;

For the edit made AFTER I answered, you just follow the same idea:

select hostname,
       count(*) filter (where status = 'C') as num_c,
       count(*) filter (where status = 'NC') as num_nc,
       count(*),
       avg( (status = 'C')::int ) as c_ratio
from t
group by hostname;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Can I get the C% as well like this: hostname | C total| NC total | Total (C+NC) | C % ---------+--------+----------+--------------+----- a1 | 2 | 1 | 3 |66.66 a2 | 1 | 2 | 3 |33.33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.