SQL aggregate function with if condition

I'm wondering if I can perform count function on different status_id with condition when status_id is X then something

This is my current query:

select count(*), status_id
from users
group by status_id

I would like to modify it to have extra condition: when users.status_id is in (18,24,25) then check if users.active = true. In all other cases no need to check the users.active column.

As of now I am doing following

select count(*), status_id
from users
where 1 = case when status_id in (18,24,25) 
           then (case when active = true then 1 else 0 end) 
          else 1 end
group by status_id

Is that the correct way to write query or there is a simpler way?

Thank you


Solution 1:

The easiest way is:

SELECT COUNT(*), status_id
FROM users
WHERE status_id NOT IN (18, 24, 25) OR active = true
GROUP BY status_id