我想计算不同值的相同字段,例如:
用户{user_id, 性别}
性别可以有明显的男性或女性:)
我想计算所有男性和女性的数量,即
COUNT(male) COUNT(female)
4 16
但我很困惑,因为它们来自同一个gender coloumn
谢谢
试试这个逐行结果:
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 |
根据您的评论,您需要计算男性、女性和总人数:
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
试试这个查询 -
SELECT
COUNT(IF(gender = 'M', User_id, NULL) males,
COUNT(IF(gender = 'F', User_id, NULL) females
FROM
User