SQL同时使用count和max函数时

huangapple go评论68阅读模式
英文:

SQL using count and max functions at the same time

问题

我要翻译的内容:

I have a query and it brings me how many people live in which country.
Select Country, COUNT(EmployeeID) from Employees group by Country

What kind of query should I use if I want to get the most populated city and the number of people living in it?

The code I tried :
Select Country, MAX(COUNT(EmployeeID)) from Employees group by Country

翻译后的内容:

我有一个查询,它告诉我每个国家有多少人居住。
选择 国家, 计数(员工ID) 从 员工表 分组按 国家

如果我想要获取人口最多的城市以及居住在其中的人数,我应该使用什么样的查询?

我尝试的代码:
选择 国家, MAX(计数(员工ID)) 从 员工表 分组按 国家

英文:

I have a query and it brings me how many people live in which country.
Select Country, COUNT(EmployeeID) from Employees group by Country

What kind of query should I use if I want to get the most populated city and the number of people living in it?

The code I tried :
Select Country, MAX(COUNT(EmployeeID)) from Employees group by Country

答案1

得分: 4

你可以使用 TOP

选择 TOP 1 Country, COUNT(EmployeeID) as [count]
从 Employees 表中
按 Country 分组
按 [count] 降序排序

英文:

You can use TOP :

Select TOP 1 Country, COUNT(EmployeeID) as [count]
from Employees
group by Country
order by [count] desc

答案2

得分: 0

尝试这个。qty - 按国家计数,maxqty - 所有国家的最大计数。

选择 Country
  ,COUNT(EmployeeID) qty
  ,MAX(COUNT(EmployeeID))over() maxqty
来自 Employees 
根据 Country 分组

对于测试数据

创建表 Employees (EmployeeId int, country varchar(20));
插入到 Employees 中的值 
 (1,'country1'),(2,'country1')
,(3,'country2'),(4,'country2'),(5,'country2')
;

结果

Country qty maxqty
country1 2 3
country2 3 3
英文:

Try this. qty - count for country, maxqty - max count for all country.

Select Country
  ,COUNT(EmployeeID) qty
  ,MAX(COUNT(EmployeeID))over() maxqty
from Employees 
group by Country

For test data

create table Employees (EmployeeId int,country varchar(20));
insert into Employees values 
 (1,'country1'),(2,'country1')
,(3,'country2'),(4,'country2'),(5,'country2')
;

Result

Country qty maxqty
country1 2 3
country2 3 3

huangapple
  • 本文由 发表于 2023年6月22日 18:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定