[英]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.