Keyword group by, Having usage

Outline

GROUP BY We can literally start to understand, GROUP represents the group, write back BY field name, it means that the fields are grouped according to which, if the words are more useful in Excel, GROUP BY more similar to Excel pivot table inside.
GROUP BY aggregate functions have to be fitted with, you can then packet count (COUNT), the summation (the SUM), averaging (AVG) and the like.

Common aggregate functions

  • count () Count
  • sum () sums
  • avg () average
  • max () maximum
  • min () Min

grammar

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value GROUP BY column_name; 

example

Next we will be understood by an example:
We now have a total of four field dept_emp table, are emp_no (employee number), dept_no (department number), from_date (start time), to_date (end time), employee records in a sector in which the time period, to_date equal representation 9999-01-01 of currently serving.

 
image.png
The number of departments

We now want to know how many of each department employees, as follows:

  1. Screening of employees where to_date='9999-01-01';
  2. Sectoral groupinggroup by dept_no
  3. Employee is counted count(emp_no)
Full statement is as follows:
SELECT
  dept_no as 部门,
  count( emp_no) as 人数
FROM dept_emp WHERE to_date = '9999-01-01' GROUP BY dept_no 
result
 
image.png
Department name

The results we obtained after step is grouped on the department number, we can go to the next step associated with the name of the department by departments, the statement is as follows:

SELECT
    ( SELECT d.dept_name FROM departments d WHERE de.dept_no = d.dept_no ) AS 部门, count( de.emp_no ) AS 人数 FROM dept_emp de WHERE de.to_date = '9999-01-01' GROUP BY de.dept_no 
result
 
image.png
HAVING

当然提到GROUP BY 我们就不得不提到HAVING,HAVING相当于条件筛选,但它与WHERE筛选不同,HAVING是对于GROUP BY对象进行筛选。
我们举个例子:
每个部门人数都有了,那如果我们想要进一步知道员工人数大于30000的部门是哪些,这个时候就得用到HAVING了。
语句如下:

SELECT
    ( SELECT d.dept_name FROM departments d WHERE de.dept_no = d.dept_no ) AS 部门, count( de.emp_no ) AS 人数 FROM dept_emp de WHERE de.to_date = '9999-01-01' GROUP BY de.dept_no HAVING count( de.emp_no ) > 30000 
结果
 
 

 

Guess you like

Origin www.cnblogs.com/mark5/p/11115750.html
Recommended