2

我有下表:

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

现在我想计算哪种性别更喜欢哪种饮料。结果应如下所示:

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

有人有想法吗?

提前感谢您的建议。

4

1 回答 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 演示

上面的查询可以进一步转换为准备好的语句。这很有帮助,例如,如果您设法在不修改原始查询的情况下为性别添加另一个值(例如,u对于中性)。例子,

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 演示

于 2012-10-28T23:46:27.590 回答