Home  >  Article  >  Database  >  Usage of group by in sql

Usage of group by in sql

下次还敢
下次还敢Original
2024-04-29 14:54:131171browse

GROUP BY in SQL is used to group data sets and perform summary operations. The grouping column specifies the column of the grouped data set, while the summary operation specifies the operation to perform (such as a sum or count). Example: SELECT product_category, SUM(quantity_sold) FROM sales_table GROUP BY product_category; Group sales by product category and calculate total sales for each category.

Usage of group by in sql

Usage of GROUP BY in SQL

The GROUP BY clause is used to group the data set so that each Groups perform summary operations such as sums, averages, or counts.

Syntax:

<code class="sql">SELECT column_list
FROM table_name
WHERE condition
GROUP BY group_by_column_list</code>

Usage:

  1. Specify group group column (group_by_column_list): This list specifies the columns used to group the dataset.
  2. Perform summary operation (column_list): This list specifies the summary operation to be performed on each group, for example:

    • SUM(): Sum
    • AVG(): Average
    • COUNT(): Count

Example:

Calculate total sales for each product category:

<code class="sql">SELECT product_category, SUM(quantity_sold)
FROM sales_table
GROUP BY product_category;</code>

The output will group each product category and show the total sales for each category.

Other notes:

  • Multiple group columns can be combined, for example: GROUP BY product_category, product_name.
  • Summary operations can only be applied to group group columns.
  • If you want to apply summary operations to all rows, you can use GROUP BY 1, where 1 represents the first column of the data set.
  • You can use aggregate functions in the GROUP BY clause, such as MIN() and MAX().

The above is the detailed content of Usage of group by in sql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn