The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.
GROUP BY子句可用在SELECT的多條結果中選擇數據並且將數據組織成一列或幾列。
The syntax for the GROUP BY clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n;aggregate_function can be a function such as
SUM,
COUNT,
MIN, or
MAX.
Example using the SUM functionFor example, you could also use the SUM function to return the name of the department and the total sales (in the associated department).
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department;Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function, you must use a GROUP BY clause. The department fIEld must, therefore, be listed in the GROUP BY section.
Example using the COUNT functionFor example,