Sobes.tech
Junior — Middle

How to use aggregate functions together with the GROUP BY operator for data grouping?

sobes.tech AI

Answer from AI

Aggregate functions in SQL (e.g., COUNT(), SUM(), AVG(), MIN(), MAX()) are used together with the GROUP BY clause to group rows by one or more columns and compute aggregated values for each group.

Example: suppose there is a table orders with columns customer_id and amount. To find the total order amount for each customer, you write:

SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;

Here, GROUP BY customer_id groups the rows by customers, and SUM(amount) calculates the total orders in each group.

In Java, when working with databases via JDBC or ORM (e.g., JPA), you can use such queries to retrieve aggregated data. If you are grouping and aggregating in Java code, for example using Stream API, you can use methods like collect(Collectors.groupingBy(..., Collectors.summingInt(...))) and similar.