[英]How to get MIN/MAX with subquery
I have three tables like these 我有三个这样的桌子
employee_ID(Pk) | employee_ID(Pk)| department_ID(Fk) department_ID(Fk)
department_ID(Pk) | department_ID(Pk)| location_ID(Fk) location_ID(Fk)
location_ID(Pk) | location_ID(Pk)| city 市
What I want is the name of the city that has least employees. 我想要的是员工最少的城市的名字。 I've try something like the following sql below : 我已经尝试过类似以下的sql:
SELECT l.city FROM employees e, departments d, locations l WHERE e.department_ID = d.department_ID AND d.location_ID = l.location_ID GROUP BY l.city ORDER BY 2 LIMIT 1
But that's not a good one. 但这不是一个好选择。 I want it in the subquery and MIN function maybe COUNT function.I tried it but couldn't figure it out. 我想在子查询中使用它,而MIN函数也许是COUNT函数。我尝试了一下,但找不到。 Any ideas? 有任何想法吗? Thanks a lot! 非常感谢!
You were pretty close. 你很近。 Try this: 尝试这个:
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
order by no_of_employees asc
limit 1
Example: 例:
create table locations (location_id int, city varchar(20));
insert into locations values (1, 'LA'), (2, 'NY');
create table departments (department_id int, location_id int);
insert into departments values (1, 1), (2, 1), (3, 2), (4, 2);
create table employees (employee_id int, department_id int);
insert into employees values (1, 1), (2, 1), (3, 1), (4, 3), (5, 4);
Result of the query:
| city | no_of_employees |
|------|-----------------|
| NY | 2 |
SQLFiddle example: http://sqlfiddle.com/#!9/75aa1/1 SQLFiddle示例: http ://sqlfiddle.com/#!9/75aa1/1
Using subquery as per requested in the comment, here's how you could do it - but don't do it! 按照注释中的要求使用子查询,这是您可以执行的操作-但不要这样做! Use subquery only if needed. 仅在需要时使用子查询。
select * from (
-- get list of all city and employee count here
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
) subquery1
-- compare the no of employees with min. employees from the same query
where no_of_employees = (
-- find minimum number of employees here
select min(no_of_employees) from (
-- same query as subquery1
select l.city, count(*) as no_of_employees
from locations l
inner join departments d
on d.location_id = l.location_id
inner join employees e
on e.department_id = d.department_id
group by l.city
) subquery2
)
Result:
| city | no_of_employees |
|------|-----------------|
| NY | 2 |
SQLFiddle example: http://sqlfiddle.com/#!9/75aa1/4 SQLFiddle示例: http ://sqlfiddle.com/#!9/75aa1/4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.