tags:

views:

84

answers:

1

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 |
+---------------+-------------+
+6  A: 

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
Joe Koberg