I have a table with 3 columns being country, user_id, gender.
The user_id just increments, there are a number of different countries and the gender is either male or female. Similar to this
user_id country gender
1 japan male
2 peru female
3 japan female
4 fiji male
5 peru female
I want to run one query to return a unique list of countries, the total number of user_id‘s for the country and the male and female numbers for each country. so the results would look like:
country total male female
peru 2 NUL 2
japan 2 1 1
fiji 1 1 NUL
I have tried a number of differnet queries but can’t return all the results in one query and don’t want to use 2 queries if possible.
this is my last try – I know its a mess but I was trying anything:
SELECT DISTINCT a.country AS country, COUNT(b.gender) AS male, COUNT(c.gender) AS female, COUNT(a.user_id) AS total
FROM userattributes as a
LEFT JOIN userattributes as b ON a.user_id=b.user_id
LEFT JOIN userattributes as c ON a.user_id=c.user_id
WHERE b.gender='male' AND c.gender='female'
GROUP BY country;
Can anyone do the above in one SELECT?
thx
There’s no need to
JOINthe table with itself. Using aCASEexpression with theSUMaggregate would suffice.