Sobes.tech
Junior

Mis on GROUP BY operaator ja millist rolli see SQL-is mängib?

sobes.tech AI

Vastus AI-lt

GROUP BY in SQL is used to group rows with identical values in one or more columns.

Its role:

  • Data aggregation: Allows applying aggregate functions like COUNT, SUM, AVG, MIN, MAX to each group. This enables obtaining summarized data by categories.
  • Getting unique combinations: Can be used to identify unique value combinations in specified columns.
  • Sorting results: Often used together with ORDER BY to sort grouped results.

Example of usage:

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

Here, GROUP BY department groups rows by the value in the department column, and COUNT(*) counts the number of employees in each group.

Important: in the SELECT list, either columns specified in GROUP BY or the results of aggregate functions should be included.