首页 > 解决方案 > 使用条件计算表中的字段

问题描述

因此,我正在尝试根据一个类似于下表但包含世界各地更多国家的表格来锻炼如何计算计数。-

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

标签: sqlsql-servercount

解决方案


使用 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

查看演示


推荐阅读