SQL:SQL Multirow Aggregate Metrics Calculation: COUNT, SUM, AVG, and GROUP BY
SQL•Functions

SQL Multirow Aggregate Metrics Calculation: COUNT, SUM, AVG, and GROUP BY

SQL aggregate functions collapse multiple table rows into single summary metrics per partition. When combined with GROUP BY and HAVING clauses, they form the backbone of analytical query pipelines, calculating volume, revenue, averages, and statistical boundaries.

Syntax

SELECT category, COUNT(*) AS volume, ROUND(AVG(cost), 2) AS avg_cost FROM cloud_services GROUP BY category HAVING COUNT(*) > 1;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
COUNT(*)Aggregate FunctionComputes total rows in the partition, including rows with nulls.
SUM(col) / AVG(col)Aggregate FunctionCalculates arithmetic sum and average of non-null column values.
HAVING conditionClauseFilters aggregated partitions after GROUP BY calculation occurs.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

-- 1. Cloud infrastructure inventory dataset
CREATE TABLE cloud_nodes (
    id INTEGER PRIMARY KEY,
    cluster_tier TEXT,
    allocated_cores INTEGER,
    monthly_cost REAL
);

INSERT INTO cloud_nodes VALUES
    (1, 'PRODUCTION', 64, 450.00),
    (2, 'PRODUCTION', 32, 220.00),
    (3, 'STAGING',    16,  95.00),
    (4, 'STAGING',     8,  55.00),
    (5, 'ANALYTICS',  128, 920.00);

-- 2. Multirow aggregate calculation partitioned by cluster_tier
SELECT 
    cluster_tier,
    COUNT(*) AS total_nodes,
    SUM(allocated_cores) AS total_cores,
    ROUND(SUM(monthly_cost), 2) AS total_cost_usd,
    ROUND(AVG(monthly_cost), 2) AS avg_node_cost_usd,
    MIN(monthly_cost) AS cheapest_node_cost,
    MAX(monthly_cost) AS peak_node_cost
FROM cloud_nodes
GROUP BY cluster_tier
HAVING COUNT(*) >= 2
ORDER BY total_cost_usd DESC;
Expected Output:
cluster_tier  total_nodes  total_cores  total_cost_usd  avg_node_cost_usd  cheapest_node_cost  peak_node_cost
------------  -----------  -----------  --------------  -----------------  ------------------  --------------
PRODUCTION    2            96           670.0           335.0              220.0               450.0         
STAGING       2            24           150.0           75.0               55.0                95.0          

How It Works: Step-by-Step

  • Lines 2-14: Defines schema and populates sample cloud node infrastructure metrics.
  • Lines 17-26: Calculates COUNT, SUM, AVG, MIN, and MAX across partitions grouped by cluster_tier.
  • Line 27: HAVING filter retains only tiers with 2 or more nodes (excluding single-node ANALYTICS tier).

Key Concepts

  • Aggregate functions process multiple records and return a single scalar value per group.
  • WHERE filters individual table rows BEFORE grouping; HAVING filters aggregated groups AFTER calculations.
  • COUNT(*) includes all rows in the group, whereas COUNT(column) ignores rows where that column is NULL.
  • Always include non-aggregated SELECT columns in the GROUP BY clause to comply with standard SQL standards.

Common Mistake: Filtering aggregate metrics inside the WHERE clause instead of HAVING

WHERE clauses execute before aggregation occurs and cannot reference aggregate function results like SUM() or COUNT(). Use HAVING instead.

❌ Incorrect
SELECT tier, SUM(cost) FROM nodes WHERE SUM(cost) > 500 GROUP BY tier; // Syntax Error!
✅ Correct
SELECT tier, SUM(cost) FROM nodes GROUP BY tier HAVING SUM(cost) > 500; // Correct

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler