简体   繁体   中英

Group by multiple columns : SQL

I have a table:

在此处输入图像描述

I have a query which gives me

在此处输入图像描述

And I want something like this:

在此处输入图像描述

Query used for above result is:

select ucountry,sum(Males) Males,sum(females ) Females from (
                                                  select ucountry,
                                                         case when gender = 'M' then count(1) else 0 end as Males,
                                                         case when gender = 'F' then count(1) else 0 end as females
                                                  from testing.test_users
                                                  group by ucountry, gender
                                              ) a group by ucountry;

I am definitely not doing the best thing here. Any thing you guys think would be better?

If you're trying to count the number of males and females in each country:

select ucountry,
sum(case when gender = 'M' then 1 else 0 end) as males,
sum(case when gender = 'F' then 1 else 0 end) as females
from testing.test_users
group by ucountry

If you are using PostgreSQL then you can also user FILTER

select ucountry, COUNT(*) FILTER (WHERE gender = 'M') males, 
COUNT(*) FILTER (WHERE gender = 'F') females from testing.test_users group by ucountry

You should apply GROUP BY only on ucountry column. Use below query to get expected result in SQL Server :

SELECT  
    ucountry, 
    SUM(IIF(Name = 'M', 1, 0)) males,
    SUM(IIF(Name = 'F', 1, 0)) females
FROM testing.test_users
GROUP BY ucountry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM