sqlcmd.net validated sql reference
intermediate aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Calculate A Weighted Average

Divide the sum of value times weight by the sum of weights instead of averaging pre-aggregated values.

Docker-validated Not currently validation-green

Average product scores by response count

The Basic product does not average to 90 because the score of 100 came from three times as many responses as the score of 80. Its weighted score is (80 10 + 100 30) / 40 = 95.

Rows loaded before the example query runs.
Setup
CREATE TABLE rating_batches (product VARCHAR(20), score INT, responses INT);

INSERT INTO
  rating_batches (product, score, responses)
VALUES
  ('Basic', 80, 10),
  ('Basic', 100, 30),
  ('Pro', 70, 20),
  ('Pro', 90, 20);
Shared across supported engines.
SQL
SELECT
  product,
  SUM(score * responses) / SUM(responses) AS weighted_score
FROM
  rating_batches
GROUP BY
  product
ORDER BY
  product;
Returned rows for the shared example.
productweighted_score
Basic95
Pro80

The examples use values whose weighted averages are whole numbers, avoiding engine-specific decimal display differences.

Where this command helps.

  • combining product ratings when each rating bucket has a different response count
  • averaging rates or scores without giving small groups the same influence as large groups

What the command is doing.

A weighted average gives larger groups or more important observations more influence than smaller ones. The core formula is SUM(value * weight) / SUM(weight). This is different from AVG(value), which treats every row equally and can produce misleading results when each row represents a different number of observations.