【问题标题】:How to get MIN/MAX with subquery如何使用子查询获取 MIN/MAX
【发布时间】:2015-09-23 17:54:17
【问题描述】:

我有三张这样的桌子

员工

employee_ID(Pk) |部门ID(Fk)

部门

department_ID(Pk) | location_ID(Fk)

地点

location_ID(Pk) |城市

我想要的是员工最少的城市的名称。 我尝试了类似下面的 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

但这不是一个好主意。我希望它在子查询和 MIN 函数中可能是 COUNT 函数。我尝试过但无法弄清楚。 有任何想法吗? 非常感谢!

【问题讨论】:

    标签: mysql sql aggregate-functions


    【解决方案1】:

    你已经很接近了。试试这个:

    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
    

    例子:

    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 示例:http://sqlfiddle.com/#!9/75aa1/1

    按照评论中的要求使用子查询,您可以这样做 - 但不要这样做!仅在需要时使用子查询。

    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 示例:http://sqlfiddle.com/#!9/75aa1/4

    【讨论】:

    • 它有效,谢谢。但它可以通过子查询方式完成吗?我尝试了子查询,但无法正常工作。
    • 尽可能避免子查询。我添加了一个例子
    • 太棒了!!我认为如果多个城市的最低员工人数相同,子查询会有所帮助。还是还有其他的?
    • @BBCh1 如果您发现此答案有用,请随时将其标记为已接受以结束此问题
    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 2017-06-10
    • 1970-01-01
    • 2016-11-24
    • 2017-01-01
    • 1970-01-01
    • 2014-12-31
    • 2017-11-05
    相关资源
    最近更新 更多