SQL group by usage and group by syntax

Source: Internet
Author: User

In the SQL SQL Aggregate functions that use the same number of statements together provide some database tutorial columns for grouping (the result dataset method ).

GROUP

 

 

The best way to use SQLGROUPStatement example.

The following database table is called EmployeeHours to store the daily time of each employee:

Employee Date Hours
John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 8
John Smith 5/7/2004 9
Allan Babel 5/7/2004 8
Tina Crown 5/7/2004 10
John Smith 5/8/2004 8
Allan Babel 5/8/2004 8
Tina Crown 5/8/2004 9

If the company manager wants to overlay all the work hours of all employees, he needs to execute the following SQL statement:

Select sum (Hours)
FROM EmployeeHours

But what if the manager wants to get the sum of his employees for every time?
Therefore, he needs to modify his SQL query and useGROUPStatement:

SELECT Employee, SUM (Hours)
FROM EmployeeHours
Group by Employee

The result of the SQL expression will be the following:

Employee Hours
John Smith 25
Allan Babel 24
Tina Crown 27

 

As you can see, we only work for each employee, because we are grouped by the employee column.

The SQLGroup by sub-Statement can be used for other SQL Aggregate functions, such as AVG of SQL:

SELECT Employee, AVG (Hours)
FROM EmployeeHours
Group by Employee

Employee Hours
John Smith 8.33
Allan Babel 8
Tina Crown 9

In the date column of our employee table, we can also group to find out what is the total number of hours from the date of each job to the table:

SELECT Date, SUM (Hours)
FROM EmployeeHours
Group by Date

Here is the result of the above SQL expression:

Date Hours
5/6/2004 24
5/7/2004 27
5/8/2004 25

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.