简体   繁体   English

如何使用计数并一起区分

[英]how to use count and distinct together

I have a table with names of countries. 我有一张有国家名称的表格。 The country names are duplicated in the table. 国家名称在表中重复。 Eg say there are 8 rows in the table, 5 rows with country Germany and 3 with country UK . 例如,表中有8行,与国家( Germany 5行,与UK (国家)有关的行为3行。 I want to get count the countries in the table (eg. I should get the number 2). 我想对表格中的国家进行计数(例如,我应该得到数字2)。 But I am unable to come up with the query 但我无法提出查询

I tried SELECT Country FROM Customers; 我尝试SELECT Country FROM Customers; but that will give me 8 rows. 但这会给我8行。 I tried SELECT DISTINCT Country FROM Customers; 我尝试SELECT DISTINCT Country FROM Customers; but that gives me 2 rows. 但这给了我2行。 I tried using count as SELECT DISTINCT Count(Country) FROM Customers; 我尝试使用count作为SELECT DISTINCT Count(Country) FROM Customers; but I get 8 (probably because DISTINCT is applied on result set of SELECT Count(Country) FROM Customers; How could I get 2 ? 但是我得到8(可能是因为DISTINCT应用于SELECT Count(Country) FROM Customers;SELECT Count(Country) FROM Customers;结果集SELECT Count(Country) FROM Customers;我如何得到2

You can use distinct inside count: 您可以使用distinct内部计数:

select count(distinct country)
from customers;

Which is equivalent to: 等效于:

select count(*)
from (  
  select distinct country
  from customers
  where country is not null
) t;

在不同的内部使用

SELECT count( distinct Country) FROM Customers

You can use distinct country within count as below: 您可以在以下范围内使用不同的国家/地区:

SELECT count(DISTINCT country)
FROM customers;

You can use distinct country within count and group by country for getting country name as well: 您还可以在计数中使用不同的国家/地区,并按国家/地区分组以获取国家/地区名称:

SELECT count(1), country
FROM customers
GROUP BY country;

Here is one way to do this using analytic functions: 这是使用解析函数执行此操作的一种方法:

SELECT ROW_NUMBER() OVER (ORDER BY COUNT(*)) cnt
FROM customers
GROUP BY country
ORDER BY cnt DESC
LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM