sql - 在 SQL 中计数时如何分隔列?
问题描述
如何使用 SQL 中的查询将国家/地区的数量分别计算到不同的列中?
列中的所有国家:
Countries
US
Spain
Germany
US
Mexico
国家总数显示为:
墨西哥 1 美国 2 西班牙 1 德国 1
我正在尝试使用这样的查询:
SELECT COUNT(Country) AS 'Mexico', COUNT(Country) AS 'USA', COUNT(Country) AS 'Spain', COUNT(Country) AS 'Germany'
FROM Customers
WHERE Country='Mexico' AND Country='US' AND Country='Spain' AND Country='Germany';
结果显示为:
墨西哥 0 美国 0 西班牙 0 德国 0
有人帮我吗?
解决方案
使用条件聚合:
select sum(case when country = 'Mexico' then 1 else 0 end) as mexico,
sum(case when country = 'USA' then 1 else 0 end) as usa,
sum(case when country = 'Spain' then 1 else 0 end) as spain,
sum(case when country = 'German' then 1 else 0 end) as german
from Customers;
推荐阅读
- amazon-web-services - 防止 Auto Scaling 组向 CloudFormation 报告成功,直到 EC2 和 ELB 运行状况检查至少通过一次
- caching - 您应该在分布式远程缓存中监控哪些关键指标,以评估其健康状况?
- javascript - react native & firestore - 返回 vs console.log
- r - 通过 R 中的包装器传递参数
- javascript - 尝试播放音频文件时 Safari 中的网络连接错误
- javascript - 将 h-captcha 令牌发送到网站,按下提交按钮。硒蟒
- c++ - 对象,向量的c ++排序问题
- javascript - Jquery .css() 不起作用(可能是由其他原因引起的)
- google-custom-search - 如何在 Google 可编程站点搜索中删除某些 URL 模式
- javascript - 如何使用 react-redux 实现 addItem