(2)mysql -- query the Department with the largest number of people

Keywords: SQL

sketch:
Find out the Department with more than or equal to 10 people.
main points
On the basis of the previous article, we will examine the use of having. Previous link: http://blog.csdn.net/lovesummerforever/article/details/78806765

1. Function count() + group by.

2. having query.

3. The table structure and the added data are as follows.

-- ----------------------------
-- Table structure for employee_info
-- ----------------------------
DROP TABLE IF EXISTS `employee_info`;
CREATE TABLE `employee_info` (
  `employee_id` int(10) NOT NULL,
  `department_id` int(10) NOT NULL,
  PRIMARY KEY (`employee_id`,`department_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of employee_info
-- ----------------------------
INSERT INTO `employee_info` VALUES ('1', '2');
INSERT INTO `employee_info` VALUES ('2', '2');
INSERT INTO `employee_info` VALUES ('3', '2');
INSERT INTO `employee_info` VALUES ('4', '1');
INSERT INTO `employee_info` VALUES ('5', '1');
INSERT INTO `employee_info` VALUES ('6', '2');
INSERT INTO `employee_info` VALUES ('7', '2');
INSERT INTO `employee_info` VALUES ('8', '2');
INSERT INTO `employee_info` VALUES ('9', '2');
INSERT INTO `employee_info` VALUES ('10', '2');
INSERT INTO `employee_info` VALUES ('11', '2');
INSERT INTO `employee_info` VALUES ('12', '2');
INSERT INTO `employee_info` VALUES ('13', '3');
INSERT INTO `employee_info` VALUES ('14', '3');
INSERT INTO `employee_info` VALUES ('15', '3');
INSERT INTO `employee_info` VALUES ('16', '3');
INSERT INTO `employee_info` VALUES ('17', '3');
INSERT INTO `employee_info` VALUES ('18', '3');
INSERT INTO `employee_info` VALUES ('19', '3');
INSERT INTO `employee_info` VALUES ('20', '3');
INSERT INTO `employee_info` VALUES ('21', '3');
INSERT INTO `employee_info` VALUES ('22', '3');
INSERT INTO `employee_info` VALUES ('23', '3');

thinking
1) The first is to summarize the number of department personnel according to the Department id.

select COUNT(employee_id) as number  ,department_id from employee_info group by  department_id 

2) where can't be used after group by, and having can be used, so the final sql is as follows.

select COUNT(employee_id) as number  ,department_id from employee_info group by  department_id   HAVING number>=10;

Summary:
Although the road is endless and faraway, I still want to pursue the truth in the world.
If we meet such a problem, we should divide the big problems into small ones one by one, then solve the small ones one by one, and then put them together, then the big problems can be solved.

Posted by NSH on Mon, 25 May 2020 08:12:30 -0700