Sobes.tech
Junior

What SQL query should be used to group data?

sobes.tech AI

Answer from AI

SELECT
    column1,
    column2,
    aggregate_function(column3)
FROM
    your_table
WHERE
    condition
GROUP BY
    column1,
    column2
ORDER BY
    column1;

GROUP BY is used to group rows with the same values in one or more columns into a single summary row, for which aggregate functions (such as COUNT, SUM, AVG, MIN, MAX) can be applied.

  • SELECT - specifies the columns to be selected. Must include columns for grouping and/or aggregate functions.
  • FROM - specifies the table from which data is selected.
  • WHERE - optional condition to filter rows before grouping.
  • GROUP BY - specifies the columns to group data by. All non-aggregated columns in SELECT must be included in GROUP BY.
  • HAVING - optional condition to filter groups after grouping (used with aggregate functions).
  • ORDER BY - optional condition to sort the resulting rows.

Example of aggregate functions:

Function Description
COUNT() Counts the number of rows in a group.
SUM() Calculates the sum of values in a column for each group.
AVG() Calculates the average value in a column for each group.
MIN() Finds the minimum value in a column for each group.
MAX() Finds the maximum value in a column for each group.