Skip to content
Advertisement

SQL Weighted averages of multiple rows –

How would you go about to find the real weighted average of multiple rows:

By real weighted, I mean like this calculator: https://www.rapidtables.com/calc/math/weighted-average-calculator.html (and not by multiplying value with weight).

enter image description here

The weight for each answer is set in answers and values for each question in child-table answer_items. We want the weighted average for each question (a,b,c,d). We know what questions to look for in advance.

The query will include between 2 and 500k answers (so preferably a speedy solution 🙂 )

Advertisement

Answer

You can multiply the value times the weight and then divide by the sum of the weights. For the weighted average by question:

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement