1

I have a table like this in mysql:

dancer1 | dancer2
------------------
jeff    | Julia
john    | Megan
jeff    | Vanessa

I should be easy, but how do I count the number of unique dancers (in this case 5) The problem looks like questionned here: MySQL Counting Distinct Values on Multiple Columns, but not quite

1
  • you need the count as 5 as given here..? Commented Aug 31, 2016 at 12:54

3 Answers 3

2

A simple union will give you a set of all dancers:

select DISTINCT dancer1 as dancer from table
union 
select DISTINCT dancer2 as dancer from table

And if you want the count:

select count(all_dancers.dancer) from (    
     select DISTINCT dancer1 as dancer from table
     union 
     select DISTINCT dancer2 as dancer from table
) all_dancers
Sign up to request clarification or add additional context in comments.

2 Comments

@safinchacko I don't think a distinct is possible on multiple columns at the same time. I just tried it out in MySQL
Only with UNION the count is right, thanks @shravster !
0

try this query

select  count( distinct dancer1,dancer2  ) from table 

Comments

0
SELECT COUNT(DISTINCT dancer) 
  FROM 
     ( SELECT dancer1 dancer 
         FROM my_table 
        UNION 
       SELECT dancer2 
         FROM my_table
     ) x;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.