PostgreSQL从平均值中排除值

4si2a6ki  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(160)

我正在计算一个表中数值的平均值

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}

如何从平均值的计算中排除大于1000或小于0的值?
我得到内部服务器错误,当我尝试

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}
mwg9r5ms

mwg9r5ms1#

你可以简单地添加一个WHERE predicate :

SELECT AVG(measurement) AS average FROM measurements
  WHERE measurement >= 0 AND measurement <= 1000
ghhaqwfi

ghhaqwfi2#

前面的答案是正确的,但现代版本的Postgres也支持:

SELECT AVG(measurement) AS overall_average
, AVG(measurement) FILTER(WHERE measurement >= 0 AND measurement <= 1000 ) as between_average
FROM measurements
WHERE TRUE;

这很好,因为它可以让您轻松地在同一个查询中返回不同的平均值,最坏的情况下,只需要对表进行一次扫描,而不是进行多个查询。当然,如果你只是得到一个average-within-a-range值,那么在WHERE子句中过滤数据意味着Postgres很容易更早地过滤数据。有关更多信息,请参见聚合表达式文档。

相关问题