0

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;
3
  • 1
    Have you looked at this question: stackoverflow.com/questions/5396498/…
    – user212533
    Commented Jul 29, 2020 at 17:37
  • That helped me cleanup the count of true, I use SELECT count(CASE WHEN is_jump THEN 1 END) FROM action where user_id=6. I am trying to combined each count into a column in the result table.
    – zumzum
    Commented Jul 29, 2020 at 18:09
  • Have you tried using multiple COUNTs in your query?
    – user212533
    Commented Jul 29, 2020 at 18:19

1 Answer 1

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;
1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.