0

idI have a table like this

|----|-----------|--------|
| ID | Ethnicity | Gender |
| 1  |    2      |   1    |
| 2  |    3      |   1    |
| 3  |    4      |   2    |
|----|-----------|--------|
etc ....

And I'm trying to get back a set of results that show me ethnicities group by male(1) and female(2)

So the result row would in this example would be:

Ethnicity    Male    Female
    2         1        0
    3         1        0
    4         0        1

So far I'm close with to what I want with:

SELECT ethnicity, 
(SELECT 
        count(id)
    FROM
        table_name
    WHERE
        gender = '2' ) as female,
(SELECT 
        count(id)
    FROM
        table_name
    WHERE
        gender = '1') as male
FROM table_name
GROUP BY ethnicity

Which gives me:

Ethnicity    Male    Female
2            2        1
3            2        1
4            2        1

But need the count(id) to only be a count of the adno of that ethnicity row if that makes sense.

0

2 Answers 2

2

Try this instead:

SELECT 
  ethnicity, 
  SUM(CASE WHEN gender = 1 THEN 1 ELSE 0 END) AS female,
  SUM(CASE WHEN gender = 2 THEN 1 ELSE 0 END) AS Male
FROM students
GROUP BY ethnicity;

The above should work in virtually any SQL product, not just in MySQL. If you like, however, you can also use this version, which employs MySQL's implicit conversion of booleans to ints (true -> 1, false -> 0):

SELECT 
  ethnicity, 
  SUM(gender = 1) AS female,
  SUM(gender = 2) AS Male
FROM students
GROUP BY ethnicity;
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry the 1's and 0's are misleading, I'm looking for a count of the rows.
Don't you mean SUM instead of MAX?
@timothystringer then use SUM instead of MAX like in my edit.
@AndriyM - Thanks for your edit, and thank for the tip. Didn't know that.
This (where the number of columns is known and finite) is an appropriate use of a PIVOT query. More generally, I think it's best to simply group the results (in this case by ethnicity AND gender) and handle the display logic at the application level.
0
SELECT 
  ethnicity, 
  CASE WHEN gender = 1 THEN 1 ELSE 0 END AS Male,
  CASE WHEN gender = 2 THEN 1 ELSE 0 END AS Female
FROM students

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.