关于sql:从mysql表中的同一列获取计数?

getting count from the same column in a mysql table?

我想对同一字段的不同值进行计数,例如:

user{user_id, gender}

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

我想统计所有的男性和女性,即

1
2
COUNT(male)   COUNT(female)  
   4               16

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


对于行结果,请尝试此操作:

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

输出:

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

尝试此方法获取行结果,总计:

1
2
3
4
5
SELECT  (IFNull(gender,'Total')) AS gender,
COUNT(User_id) AS Count
FROM User
GROUP BY gender
WITH rollup;

输出:

1
2
3
4
5
| gender | Count |
|--------|-------|
|      F |     4 |
|      M |     2 |
|  Total |     6 |

对于列结果,请尝试此操作:

1
2
3
4
5
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;

输出:

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

。看这个摆弄


根据您的意见,您需要计算男性、女性和总计数:

1
2
3
4
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摆弄演示


试试这个:总计数:

SQL小提琴演示


尝试此查询-

1
2
3
4
5
SELECT
  COUNT(IF(gender = 'M', User_id, NULL) males,
  COUNT(IF(gender = 'F', User_id, NULL) females
FROM
  User