开发者

get average male and femal for user table mysql

how can I write a query to get total users, %female, %male from a user table. I have a user table 开发者_运维知识库having male and female column in it.


There's not really enough specific information to go on, so it'll have to be pseudo-code, I'm afraid:

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

If each row can only be Male or Female, %female = 100 - %male.


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)

EDIT: Added calculation for percentages too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜