繁体   English   中英

按多列分组:SQL

[英]Group by multiple columns : SQL

我有一张桌子:

在此处输入图像描述

我有一个查询给了我

在此处输入图像描述

我想要这样的东西:

在此处输入图像描述

用于上述结果的查询是:

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 服务器中获得预期结果:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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