从mysql表中的同一列获取计数?

时间:2012-08-16 11:59:44

标签: mysql sql database

我想为不同的值计算相同的字段,例如:

  

用户{user_id,性别}

性别可以有明显的男性或女性:)

我希望得到所有男性和女性的统计数据,即

COUNT(male)   COUNT(female)  
   4               16

但我很困惑,因为它们来自同一个gender coloumn谢谢

4 个答案:

答案 0 :(得分:11)

尝试使用行方式结果:

SELECT gender, COUNT(User_id) AS count
FROM User
GROUP BY gender;

输出:

| gender | count |
|--------|-------|
|      F |     4 |
|      M |     2 |

尝试使用总计的行方式结果:

SELECT  (IFNull(gender,'Total')) AS gender,
COUNT(User_id) AS Count
FROM User
GROUP BY gender
WITH rollup;

输出:

| gender | Count |
|--------|-------|
|      F |     4 |
|      M |     2 |
|  Total |     6 |

尝试以列方式结果:

SELECT
  COUNT(CASE WHEN gender = 'M' THEN User_id END) AS males,
  COUNT(CASE WHEN gender = 'F' THEN User_id END) AS females,
  COUNT(*) AS Total
FROM User;

输出:

| males | females | Total |
|-------|---------|-------|
|     2 |       4 |     6 |

See this SQLFiddle

答案 1 :(得分:3)

根据您的评论,您需要计算男性,女性和总人数:

SELECT sum(case when gender = 'M' then 1 else 0 end) males,
  sum(case when gender = 'F' then 1 else 0 end) females,
  count(*) total
FROM  yourTable

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

尝试此查询 -

SELECT
  COUNT(IF(gender = 'M', User_id, NULL) males,
  COUNT(IF(gender = 'F', User_id, NULL) females
FROM
  User

答案 3 :(得分:0)

试试这个: 总数:

Select gender,count(*) as count
From User
Group by gender
with rollup

SQl Fiddle demo