6

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

用户{user_id, 性别}

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

我想计算所有男性和女性的数量,即

COUNT(male)   COUNT(female)  
   4               16

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

4

4 回答 4

13

试试这个逐行结果:

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 |

看到这个 SQLFiddle

于 2012-08-16T12:01:42.533 回答
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 Fiddle

于 2012-08-16T12:07:43.300 回答
1

试试这个查询 -

SELECT
  COUNT(IF(gender = 'M', User_id, NULL) males,
  COUNT(IF(gender = 'F', User_id, NULL) females
FROM
  User
于 2012-08-16T12:03:42.093 回答
0

试试这个:总计数:

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

SQL 小提琴演示

于 2012-08-16T12:09:01.020 回答