2

I have the following table:

+----+----------+------------+
| id | drink    | gender     |
+----+----------+------------+
|  1 | Beer     | m          |
|  2 | Milk     | f          |
|  3 | Milk     | f          |
|  4 | Tea      | m          |
+----+----------+------------+

Now I want to count which gender prefers which drink. The result should look like this:

+-------+-------+--------+
| drink | fem   | male   |
+-------+-------+--------+
|  Beer | 0     | 1      |
|  Milk | 2     | 0      |
|  Tea  | 0     | 1      |
+----+----------+--------+

Has anyone an idea?

Thanks in advance for your suggestions.

1 Answer 1

4
SELECT drink,
       SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) fem,
       SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) male
FROM tableName
GROUP BY drink

SQLFiddle Demo

the query above can be further be converted into prepared statement. This is helpful, if for instance, you manage to add another value for the gender (eg. u for unisex) without modifying the original query. example,

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when gender = ''',
      gender,
      ''' then 1 ELSE 0 end) AS ',
      gender
    )
  ) INTO @sql
FROM tableName;

SET @sql = CONCAT('SELECT drink, ', @sql, ' 
                   FROM tableName 
                   GROUP BY drink');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLFiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.