Junior — Middle
Explain the concept of data aggregation in SQL and provide examples using relevant functions.
sobes.tech AI
Answer from AI
Data aggregation in SQL is the process of combining multiple rows into one using aggregate functions to obtain summary information.
Main aggregate functions:
COUNT()— counts the number of rowsSUM()— sums the valuesAVG()— calculates the average valueMIN()— finds the minimum valueMAX()— finds the maximum value
Example: suppose there is a table sales with columns product_id and amount.
-- Count total sales
SELECT COUNT(*) FROM sales;
-- Sum of sales for each product
SELECT product_id, SUM(amount) as total_sales
FROM sales
GROUP BY product_id;
-- Average sale amount
SELECT AVG(amount) FROM sales;
Thus, aggregate functions help quickly obtain statistics and summary data from tables.