如何平均/汇总SQL查询的结果?

时间:2020-11-02 17:04:02

标签: sql postgresql

我有一个表,其中有许多行,每个行属于不同的用户。

我首先要选择属于一个用户的所有行,然后在每一行上添加该特定列的平均值,但不能使其正常工作。

我希望结果显示用户的每一行的平均值,但目前仅显示该特定行的值。

示例:

CREATE TABLE test 
(
    id INT,
    FOO INT,
    BAR INT,
    X INT,
    user_id INT
);

INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (1, 1, 2, 3, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (2, 3, 2, 1, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (3, 6, 6, 6, 1);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 100, 100, 100, 1);

INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 3000, 3000, 3000, 2);
INSERT INTO test (id, FOO, BAR, X, user_id) VALUES (4, 400, 400, 400, 2);

还有我要运行的查询:

SELECT 
    id, foo, bar, x,
    AVG(foo) AS "avg_foo",
    AVG(bar) AS "avg_bar",
    AVG(x) AS "avg_x"
FROM 
    test
WHERE
    user_id = 1
GROUP BY
    id, foo, bar, x;

但是我只是得到该行的“ foo”列中的相同数字,作为avg_foo的结果,而我试图获取每行上显示的所有“ foo”行的平均值(每次都会是相同的数字。

目前,我得到的结果是:

| id  | foo | bar | x   | avg_foo                | avg_bar              | avg_x                  |
| --- | --- | --- | --- | ---------------------- | -------------------- | ---------------------- |
| 1   | 1   | 2   | 3   | 1.00000000000000000000 | 2.0000000000000000   | 3.0000000000000000     |
| 2   | 3   | 2   | 1   | 3.0000000000000000     | 2.0000000000000000   | 1.00000000000000000000 |
| 3   | 6   | 6   | 6   | 6.0000000000000000     | 6.0000000000000000   | 6.0000000000000000     |
| 4   | 100 | 100 | 100 | 100.0000000000000000   | 100.0000000000000000 | 100.0000000000000000   |

我期望:

| id  | foo | bar | x   | avg_foo                | avg_bar              | avg_x                  |
| --- | --- | --- | --- | ---------------------- | -------------------- | ---------------------- |
| 1   | 1   | 2   | 3   | 27.5      | 27.5    | 27.5      |
| 2   | 3   | 2   | 1   | 27.5      | 27.5    | 27.5      |
| 3   | 6   | 6   | 6   | 27.5      | 27.5    | 27.5      |
| 4   | 100 | 100 | 100 | 27.5      | 27.5    | 27.5      |

---

我做了一个小提琴

https://www.db-fiddle.com/f/5tGQkqEnqB8et75eJ7NNWt/0

2 个答案:

答案 0 :(得分:0)

使用窗口功能:

SELECT id, foo, bar, x,
       avg(foo) over (partition by user_id) as "avg_foo",
       avg(bar) over (partition by user_id) as "avg_bar",
       avg(x) over (partition by user_id) as "avg_x"
FROM test
WHERE user_id = 1

答案 1 :(得分:0)

您似乎想要窗口功能:

select t.*,
    avg(foo) over() as avg_foo,
    avg(bar) over() as avg_bar,
    avg(x)   over() as avg_x
from test t
where user_id = 1