得到用户表mysql的平均男性和女性

时间:2011-08-12 09:58:42

标签: php mysql

如何编写查询以从用户表中获取总用户,%female,%male。我有一个用户表,里面有男性和女性专栏。

2 个答案:

答案 0 :(得分:2)

还没有足够的具体信息继续下去,所以它必须是伪代码,我担心:

%male = (100 * Number of Rows where sex == Male) / Total Number of Rows
%female = (100 * Number of Rows where sex == Female) / Total Number of Rows

如果每行只能是男性或女性,则%女性= 100% - 男性。

答案 1 :(得分:1)

mysql> CREATE TABLE user ( username VARCHAR(20) NOT NULL, gender ENUM('male','female') );
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO user ( username, gender ) VALUES
    -> ( 'berry', 'male' ),
    -> ( 'jessica alba', 'female' ),
    -> ( 'Sasha DiGiulian', 'female' );
Query OK, 3 rows affected (0.03 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT COUNT(username), gender FROM user GROUP BY gender;
+-----------------+--------+
| COUNT(username) | gender |
+-----------------+--------+
|               1 | male   |
|               2 | female |
+-----------------+--------+
2 rows in set (0.02 sec)


mysql> SELECT total, gender, number, ( 100 * number / total ) AS percentage FROM ( SELECT COUNT(username) AS total FROM user ) AS total, ( SELECT COUNT(username) AS number, gender FROM user GROUP BY gender ) as genders;
+-------+--------+--------+------------+
| total | gender | number | percentage |
+-------+--------+--------+------------+
|     3 | male   |      1 |    33.3333 |
|     3 | female |      2 |    66.6667 |
+-------+--------+--------+------------+
2 rows in set (0.00 sec)

编辑:也增加了百分比计算。