PostgreSQL – Get Count for Different Columns with Conditions

postgresql

I have a table, action using postgresql:

is_jump | is_throw | is_punch
true      true        false
false     true        false
false     true        true

These are all booleans.

I want to get a count for each of the actions (when true) into one result table in one query:

is_jump_count | is_throw_count | is_punch_count
     1              3                1

I can get the count for one of them at the time, that's the easy part, but, how can I combine it all in one query so that I get one result table with the counts by column like shown here?

I have implemented it this way, but, I wonder if there's a better way to accomplish this given that in the end I think I'll end up with about 15 actions to track count for…:

SELECT a.ct is_jump, b.ct is_throw
FROM
( SELECT COUNT(*) ct FROM action WHERE is_jump=true and user_id=6 ) a,
( SELECT COUNT(*) ct FROM action WHERE is_throw=true and user_id=6 ) b;

Best Answer

You can use filtered aggregation:

select count(*) filter (where is_jump) as is_jump_count,
       count(*) filter (where is_throw) as is_throw_count,
       count(*) filter (where is_punch) as is_punch_count
from the_table;