我有下表:
+----+----------+------------+
| 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 |
+----+----------+--------+
有人有想法吗?
提前感谢您的建议。
答案 0 :(得分: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
上面的查询可以进一步转换为预备语句。这很有用,例如,如果您设法为性别添加其他值(例如。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;