select语句中的MYSQL计数

时间:2012-10-10 04:21:10

标签: mysql sql database

我在数据库中有这样的数据

id  class  gender
1     A      F
2     B      F
3     A      M
4     A      F
5     A      M
6     B      M
7     A      F

从这些数据我想制作select语句来生成这样的报告

_________________________
        Gender
class   M    F     Total
_________________________
A       2    3       5
B       1    1       2
_________________________
TOTAL   3    4       7

如何制作选择陈述?

2 个答案:

答案 0 :(得分:5)

看一下以下示例

SQL Fiddle DEMO

SELECT class,
      SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) `M`,
      SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END) `F`,
      COUNT(1) Total
FROM Table1
GROUP BY class

答案 1 :(得分:2)

获取每个性别的总数:

SELECT class, gender, COUNT(*) as gender_count
FROM Gender
GROUP BY class, gender;

获得总数:

SELECT class, COUNT(*) as total_count
FROM Gender
GROUP BY class;