Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compute weighted average for selected rows in SQL

My data set has a weight column and a variable of interest var1, for which I need to form a weighted average of all rows that satisfy either var1=1 and var1=2. Unfortunately I need to do this in SQL, where I have very limited knowledge. To compute the weighted average of all rows, I would write SUM(var1 * weight)/SUM(weight). But how can I do this computation for all rows where var1 IN (1,2)?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems like what you’re looking for would be the following:

SELECT SUM(var1 * weight) / SUM(weight) 
FROM sample 
WHERE var1 in (1,2)

I created a dbfiddle where you can go and check it out.

https://www.db-fiddle.com/f/qytaC3augXijw956ReuYqb/1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading