简体   繁体   中英

how to find maximum count in a linked table

在此处输入图片说明

With the above code I want to find the maximum employees from a section BUT we can not find out how to take it ONLY with the specific name.

By this I mean that I want to have as a result only the name 'Development' and in its right the number 223.

I don not want the other departments or numbers.

I've tried many ways but I can't solve it.

In case the picture does not show well enough I give you the code I wrote below:

select dept_name, count(emp_no)
from departments 
join current_dept_emp using(dept_no)
group by dept_no;

try this one:

SET @depName = 'Development';

SELECT 
    dept_name, COUNT(emp_no)
FROM
    departments
        JOIN
    current_dept_emp USING (dept_no)
WHERE
    dept_name LIKE @depName
GROUP BY dept_no;

Or by create stored procedure to get depName as input :

DROP PROCEDURE IF EXISTS get_dept_summary;
DELIMITER //
CREATE PROCEDURE get_dept_summary(IN depName NVARCHAR(128))
BEGIN
    SELECT 
        dept_name, COUNT(emp_no)
    FROM
        departments
            JOIN
        current_dept_emp USING (dept_no)
    WHERE
        dept_name LIKE depName
    GROUP BY dept_no;

END//
DELIMITER ;

then you can call it like this:

Set @depName = 'Development';
CALL get_dept_summary(@depName);

If you don't know the name of department, just change where clause base on your requirements.

Try something like:

SELECT
    dept_name,
    count(emp_no) AS empcount
FROM
    departments
JOIN current_dept_emp USING (dept_no)
GROUP BY
    dept_no
ORDER BY
    empcount DESC
LIMIT 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM