How can I get both a subset count and a common set count in a single query?

In the simple case, suppose 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 count the number of all widgets that are enabled (enabled = 1) in the same query as the number of all widgets?

For example, if I have 3 widgets and one of them is turned on, I would like to get the results of my query, which look like this:

mysql> SELECT ... as enabled_count, ... as total_count ...
+---------------+-------------+
| enabled_count | total_count |
+---------------+-------------+
|             1 |           3 |
+---------------+-------------+
+3
source share
1 answer

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

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

If this is a different value, it is possible:

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
+11
source

Source: https://habr.com/ru/post/1704604/


All Articles