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

Usage of group by in sql

下次还敢
Release: 2024-04-29 14:54:13
Original
1253 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template