这是我的SQL查询和结果。我的要求是显示具有最多人员数的部门名称,但是我不知道该怎么做。 我想要部门名称-SE和职员计数-仅4这样的结果。
select d.department_name, count(staff_id) from department d, staff sf
where d.department_id = sf.staff_id
group by department_name
order by count(staff_id) desc
DEPARTMENT_NAME COUNT(SF.STAFF_ID)
------------------------------ ------------------
SE 4
EEE 2
IT 2
CSE 2
ECE 1
答案 0 :(得分:0)
尝试一下
别名查询
select d.department_name, count(staff_id)
from department d, staff sf
where d.department_id = sf.staff_id AND d.department_name = 'SE'
group by department_name
order by count(staff_id) desc
加入查询
select d.department_name, count(staff_id)
from department d
INNER JOIN staff sf ON d.department_id = sf.staff_id
WHERE d.department_name = 'SE'
group by department_name
order by count(staff_id) desc
LIMIT 1
或顶部
select TOP 1 d.department_name, count(staff_id)
from department d
INNER JOIN staff sf ON d.department_id = sf.staff_id
group by department_name
order by count(staff_id) desc
答案 1 :(得分:0)
您应使用LIMIT 1来减少结果,但也应使用显式联接sintax以获得更好的可读性
select d.department_name, count(staff_id)
from department d
INNER JOIN staff sf ON d.department_id = sf.staff_id
group by department_name
order by count(staff_id) desc
limit 1
或者不使用限制,您可以尝试使用最大
select d.department_name, count(staff_id) count_staff
from department d
INNER JOIN staff sf ON d.department_id = sf.staff_id
group by department_name
having count_staff = (
select max(count_staff)
from ( select d.department_name, count(staff_id) count_staff
from department d
INNER JOIN staff sf ON d.department_id = sf.staff_id
group by department_name ) t
)
答案 2 :(得分:0)
您需要首先获取每个部门的数量,然后选择数量最大的部门。因此,可以使用以下子查询:
SELECT d_name, MAX (staff_cnt)
FROM (SELECT d.department_name as d_name, count(staff_id) as staff_cnt
FROM department d, staff sf
WHERE d.department_id = sf.staff_id
GROUP BY department_name);