MySQL distinct count if conditions unique

后端 未结 2 966
耶瑟儿~
耶瑟儿~ 2021-01-31 09:36

I am trying to build a query that tells me how many distinct women and men there are in a given dataset. The person is identified by a number \'tel\'. It is possible for the sam

2条回答
  •  渐次进展
    2021-01-31 10:03

    Here's one option using a subquery with DISTINCT:

    SELECT COUNT(*) gender_count,
       SUM(IF(gender='male',1,0)) male_count,
       SUM(IF(gender='female',1,0)) female_count
    FROM (
       SELECT DISTINCT tel, gender
       FROM example_dataset
    ) t
    
    • SQL Fiddle Demo

    This will also work if you don't want to use a subquery:

    SELECT COUNT(DISTINCT tel) gender_count,
        COUNT(DISTINCT CASE WHEN gender = 'male' THEN tel END) male_count,  
        COUNT(DISTINCT CASE WHEN gender = 'female' THEN tel END) female_count
    FROM example_dataset
    
    • More Fiddle

提交回复
热议问题