Sobes.tech
Junior — Middle

Millistes SQL-päringute osades saab kasutada agregaatfunktsioone tulemuse piiramiseks?

sobes.tech AI

Vastus AI-lt

SQL aggregation functions (e.g., COUNT, SUM, AVG, MAX, MIN) can be used in the following parts of a query to limit the result:

  • In the SELECT section to compute aggregates by groups or for the entire dataset.
  • In the HAVING section to filter groups after applying aggregation functions.

Important: aggregation functions cannot be used in WHERE, as WHERE filters rows before grouping. To limit the result based on aggregates, HAVING is used.

Example:

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

Here, HAVING limits the result only to departments with more than 5 employees.