Get count for different columns with different conditions from same table into one result table?

All we need is an easy explanation of the problem, so here it is.

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;

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply