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

PostgreSQL Excluding values from average

I am calculating the average of values in a table

CREATE TABLE measurements (
  id SERIAL PRIMARY KEY,
  measurement INTEGER NOT NULL
);
import postgres from "https://deno.land/x/postgresjs@v3.3.3/mod.js";

const averageMeasurement = async() => {
    const rows =  await sql`SELECT AVG(measurement) AS average FROM measurements`;
    return rows[0].average;
}
const sql = postgres({});

export{averageMeasurement}

How can I exclude values that are larger than 1000 or smaller than 0 from the calculation of average?

I got Internal Server Error when I tried

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

import postgres from "https://deno.land/x/postgresjs@v3.3.3/mod.js";

const averageMeasurement = async() => {
    const excMeasurements = await sql`SELECT * FROM measurements WHERE measurement <= 1000 AND measurement > 0`
    const rows =  await sql`SELECT AVG(measurement) AS average FROM excMeasurements`;
    return rows[0].average;
}
const sql = postgres({});

export{averageMeasurement}

>Solution :

You can simply add a WHERE predicate:

SELECT AVG(measurement) AS average FROM measurements
  WHERE measurement >= 0 AND measurement <= 1000
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