MySQL grouping function

Source: Internet
Author: User

The group function is for a non-null value for the specified field. NOTE: Group functions cannot appear in the WHERE clause!!!

AVG ()average (only for numeric type)Max ()Maximum value (unrestricted type)Min ()Minimum value (unrestricted type)Count ()count (number of records, number of rows)StdDev ()variance (only for numeric type)SUM ()sum (only for numeric type) Prerequisites: Person Table
  1. id namedept_idsalarymanager_id
  2. 0001wangda101 8500[NULL]
  3. 0002wanger1033 000 0009
  4. 0003wangsan102 4000 0006
  5. 0004wangsi104 2000 0005
  6. 0005wangwu104 6000 0001
  7. 0006wangliu102 7000 0001
  8. 0007wangqi105 5000 0008
  9. 0008wangba105 5500 0001
  10. 0009wangjiu103 6000 0001
  11. 0010wangshi104 900 0005
  12. 0011wangsy103 5000 0009
  13. 0012wangse[NULL]3000[NULL]
Group by sort (can have one or more fields) function: Check the average salary of each department according to department
  1. SELECT
  2. dept_id,
  3. avg(salary)
  4. FROM
  5. person
  6. GROUP BY
  7. dept_id;
Results:
  1. dept_idavg(salary)
  2. [NULL]3000.000000
  3. 101 8500.000000
  4. 102 5500.000000
  5. 103 4666.666667
  6. 104 2966.666667
  7. 105 5250.000000
HavingWhen you include a group function in a query condition, it is used instead of where (note: In MySQL, the having can only be placed behind GROUP by!) )function: The Department name (Dept table), Department average salary (person table, Group function) is queried for department average salary above 5000
  1. SELECT
  2. p.dept_id,
  3. dept_name,
  4. avg(salary)
  5. FROM
  6. person p,dept d
  7. where p.dept_id = d.dept_id
  8. GROUP BY
  9. p.dept_id
  10. HAVING
  11. avg(salary)>5000;
Results:
    1. dept_iddept_nameavg(salary)
    2. 101 zongwu 8500.000000
    3. 102 zhenggong5500.000000
    4. 105 renshi 5250.000000

MySQL grouping function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.