Sobes.tech
Junior

What aggregate functions are used with grouping?

sobes.tech AI

Answer from AI

SELECT
    country,
    COUNT(*) AS number_of_customers, -- Number of records in each group
    SUM(order_total) AS total_revenue, -- Sum of values for each group
    AVG(order_total) AS average_order_value, -- Average value for each group
    MIN(registration_date) AS earliest_registration, -- Minimum value for each group
    MAX(last_order_date) AS latest_order -- Maximum value for each group
FROM
    customers
GROUP BY
    country; -- Grouping by the country column

Main aggregate functions used with GROUP BY:

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

Example table using GROUP BY and aggregate functions:

country number_of_customers total_revenue average_order_value earliest_registration latest_order
USA 150 15000.00 100.00 2020-01-15 2023-10-26
UK 75 8000.00 106.67 2019-05-20 2023-10-25
Germany 50 6000.00 120.00 2021-03-10 2023-10-26