[英]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
如果您使用的是PostgreSQL那么您也可以使用
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.您应该仅在ucountry列上应用GROUP BY 。 Use below query to get expected result in SQL Server :
使用以下查询在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.