发表投票的独特男性和女性统计

时间:2016-11-30 13:37:16

标签: mysql sql database rdbms

我想显示已经投票且允许用户多次投票的unqiue性别,items_votes中有多条记录具有相同的user_id。

下面的查询返回男性和女性的数量,但它并不是唯一的,因为如果同一男性用户多次投票,它会多次计算用户的性别。

SELECT COUNT(CASE WHEN sex = 'M' THEN items_votes.user_id END) AS males,
       COUNT(CASE WHEN sex = 'F' THEN items_votes.user_id END) AS females
    FROM items_votes
    INNER JOIN users_profiles
    ON items_votes.user_id = users_profiles.user_id
    WHERE item_id = 5

我希望从上面的查询中获得男性和女性的独特数量。

谢谢!

2 个答案:

答案 0 :(得分:4)

<强> SQL DEMO

SELECT COUNT(CASE WHEN `sex` = 'M' THEN `user_id` END) as maleCount,
       COUNT(CASE WHEN `sex` = 'F' THEN `user_id` END) as femaleCount,
       COUNT(DISTINCT CASE WHEN `sex` = 'M' THEN `user_id` END) as uniqueMaleCount,
       COUNT(DISTINCT CASE WHEN `sex` = 'F' THEN `user_id` END) as uniqueFemaleCount
FROM item     

<强>输出

| maleCount | femaleCount | uniqueMaleCount | uniqueFemaleCount |
|-----------|-------------|-----------------|-------------------|
|         5 |           5 |               3 |                 2 |

答案 1 :(得分:2)

SELECT COUNT(DISTINCT(items_votes.user_id)) AS votes, sex
FROM items_votes
INNER JOIN users_profiles
ON items_votes.user_id = users_profiles.user_id
WHERE item_id = 5
GROUP BY sex;