首页 > 解决方案 > 在 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

有人帮我吗?

标签: sqlsql-serverselectcount

解决方案


使用条件聚合:

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;

推荐阅读