sql - 使用条件计算表中的字段
问题描述
因此,我正在尝试根据一个类似于下表但包含世界各地更多国家的表格来锻炼如何计算计数。-
Country1|Country2
UK | USA
UK | USA
UK | USA
UK | UK
USA | UK
根据上表,我试图基本上像这样计算每个字段
Country1|Country2
1 | 1
1 | 1
1 | 1
1 | 0
1 | 1
我希望它回来——
CountryName | Count
UK | 5
USA | 4
正如我上面提到的,这需要是动态的,并且需要考虑到任何数量的国家。这些国家的名称都相同,因此美国将永远是美国而不是美利坚合众国。
谢谢!
编辑-为了更清楚起见,我附加了用于返回行的查询,
Select
country1
country2
FROM Country1Database c1Db
join Country2Database c2Db on c1db.MatchID = c1db.MatchID
解决方案
使用 UNION ALL:
select t.country countryname, count(*) counter from (
select country1 country from countries
union all
select country2 country from countries where country2 <> country1
) t
group by t.country
查看演示
推荐阅读
- c - 当输入的长度超过 C 字符串数组的大小时,有哪些处理方法?
- laravel - 如何在 Laravel 5.5 中重用包含 mysql 获取数据的刀片模板
- html - 角度旋转木马没有给出预期的结果
- google-cloud-dataflow - 动态扩展 Cloud Dataflow 作业
- node.js - AdonisJS 查询无法正常运行
- unix - 打印与正则表达式匹配的文件部分
- java - Maven 测试在终端上失败,但在 IntelliJ 中通过
- python - 我想将 .csv 文件转换为 Numpy 数组
- python - 使用 Python 从 JSON 获取特定字段值
- javascript - Javascript 小书签在括号中生成“SyntaxError: missing )”错误