Conditional aggregation will do it...
SELECT SUM(t.type=0) AS cnt_zero
, SUM(t.type=1) AS cnt_one
, SUM(t.type IN (0,1)) AS cnt_one_and_zero
, SUM(1) AS cnt_all
FROM mytable t
;
Note that the usage of type=0
and type=1
is MySQL-specific shorthand, which other database probably wouldn't accept.
If we ignore the handling of NULL values, this is basically equivalent to
SELECT SUM(IF( t.type=0 ,1,0)) AS cnt_zero
, SUM(IF( t.type=1 ,1,0)) AS cnt_one
, SUM(IF( t.type IN (0,1), 1,0)) AS cnt_one_and_zero
, SUM(1) AS cnt_all
FROM mytable t
;
A more ANSI standard compliant equivalent
SELECT SUM(CASE WHEN t.type=0 THEN 1 ELSE 0 END) AS cnt_zero
, SUM(CASE WHEN t.type=1 THEN 1 ELSE 0 END) AS cnt_one
, SUM(CASE WHEN t.type IN (0,1) THEN 1 ELSE 0 END) AS cnt_one_and_zero
, SUM(1) AS cnt_all
FROM mytable t
;
To get the same handling of NULL values and the same result as the first query in this answer, we could write it like this:
SELECT SUM(CASE WHEN t.type=0 THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END) AS cnt_zero
, SUM(CASE WHEN t.type=1 THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END) AS cnt_one
, SUM(CASE WHEN t.type IN (0,1) THEN 1 WHEN t.type IS NULL THEN NULL ELSE 0 END) AS cnt_one_and_zero
, SUM(1) AS cnt_all
FROM mytable t
;
In all of these, the theme remains the same: we're aggregating the results of a condition. Aka conditional aggregation.