按多列分组:SQL

Group by multiple columns : SQL

我有一个 table :

我有一个查询

我想要这样的东西:

用于上述结果的查询是:

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;

我绝对没有在这里做最好的事情。大家觉得有什么更好的吗?

如果您要计算每个国家/地区的男性和女性人数:

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

如果您正在使用 PostgreSQL 那么您还可以使用 FILTER

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

您应该仅在 ucountry 列上应用 GROUP BY。使用以下查询在 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