phpmyadmin SQL查询最大值(),计数()

amrnrhlw  于 2022-11-09  发布在  PHP
关注(0)|答案(8)|浏览(174)

数据库架构如下所示
employee(雇员姓名,街道,城市)
works(雇员_姓名,公司_名称,薪金)
company(公司名称,城市)
manages(雇员姓名,经理姓名)
需要执行的查询是:
查找员工最多的公司。
我可以通过查询找到最大计数:

SELECT max( cnt ) max_cnt
FROM (

SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
)w1;

但现在我找不到公司的名字,如果有人有什么想法,请分享。

qlzsbp2j

qlzsbp2j1#

要获取包含最大值的整行,可以使用ORDER BY ... DESC LIMIT 1代替MAX

SELECT company_name, cnt
FROM (
    SELECT company_name, count(employee_name) AS cnt
    FROM works
    GROUP BY company_name
) w1
ORDER BY cnt DESC
LIMIT 1
hgc7kmma

hgc7kmma2#

比如说:

SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
ORDER BY cnt DESC
LIMIT 1;

编辑:
针对MySQL更正了上述内容

vaj7vani

vaj7vani3#

SELECT company_name,count(*) as cnt 
FROM works 
GROUP BY company_name 
ORDER BY cnt DESC
9rbhqvlz

9rbhqvlz4#

select company_name 
from works
group by company_name
having count(distinct employee_name)>=all(select count(distinct employee_name)
from works
group by company_name )
pdsfdshx

pdsfdshx5#

以下是工作查询

Select * from(SELECT count(EmpName)cnt, CName FROM works GROUP BY CName Order By cnt desc) where ROWNUM = 1;
cigdeys3

cigdeys36#

这看起来像是一个课程问题。
如果多个公司拥有相同的最大员工数,则使用LIMIT查询将无法工作。“ORDER BY”无法过滤掉无用的信息。因此,我们有以下解决方案

SELECT company_name FROM
(SELECT company_name, count(employee_name) cnt
    FROM works
    GROUP BY company_name) 
JOIN 
(SELECT max(cnt) max_cnt
FROM (
    SELECT count(employee_name) cnt
    FROM works
    GROUP BY company_name
)) ON cnt = max_cnt
bjg7j2ky

bjg7j2ky7#

select company_name from works_for
group by company_name
having count(employee_name) = (select max(count(employee_name))from works_for
group by company_name);
kuuvgm7e

kuuvgm7e8#

在Oracle中

select company_name, count(*) as count 
    from works 
    group by company_name
    having count(*) >= all(select count(*) from works group by company_name)

相关问题