Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get both the count of a subset as well as the count of the total set in one query?

Tags:

sql

mysql

In the simple case, assume I have a table that looks like this:

mysql> describe widget; 
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| name    | varchar(255) | YES  |     | NULL    |       | 
| enabled | smallint(1)  | YES  |     | NULL    |       | 
+---------+--------------+------+-----+---------+-------+

Is it possible to get a count of all widgets that are enabled (enabled = 1) in the same query as a count of all widgets?

For instance, if I have 3 widgets totaled and one is enabled, I'd like to get the results of my query back that look like:

mysql> SELECT ... as enabled_count, ... as total_count ...
+---------------+-------------+
| enabled_count | total_count |
+---------------+-------------+
|             1 |           3 |
+---------------+-------------+
like image 932
Ian Terrell Avatar asked Dec 13 '22 05:12

Ian Terrell


1 Answers

If enabled is always 1 or 0, you can do:

SELECT 
   COUNT(*) as total_count,
   SUM(enabled) as enabled_count
 FROM widget

If it's another value, perhaps:

SELECT
   COUNT(*) as total_count,
   SUM( CASE WHEN enabled in ('enabled value 1', 'enabled value 2') 
        THEN 1
        ELSE 0
        END
      ) as enabled_count
FROM widget
like image 59
Joe Koberg Avatar answered Dec 15 '22 19:12

Joe Koberg