按两列分组并在PostgreSQL中找到另一列的平均值

moiiocjp  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(127)

我有一个问题的功能,我需要分组的两列,并采取平均另一个。
为什么下面的不起作用?

CREATE OR REPLACE FUNCTION core.cal_average_load(
  cell_load      DOUBLE PRECISION,
  id           DOUBLE PRECISION,
  s_id          DOUBLE PRECISION
) RETURNS DOUBLE PRECISION
  LANGUAGE plpgsql
AS $$
DECLARE out DOUBLE PRECISION;
  BEGIN
    out := (AVG(cell_load) OVER (PARTITION BY id, s_id));
  RETURN out;
  END;
$$;

上面返回的average_load值与cell_load值完全相同,没有任何聚合。

id    s_id   cell_load   average_load
1      1        4             6
1      1        2             6
1      1        12            6
1      2        3             4
1      2        5             4
2      1        10            4.33
2      1        1             4.33
2      2        2             3.66
2      2        3             3.66
2      2        6             3.66
bgtovc5b

bgtovc5b1#

您正在为单行调用函数。使用窗口函数仅对具有多行的数据集有意义。我认为你根本不需要函数,例如:

with my_table(id, s_id, cell_load) as (
values
    (1, 1, 1),
    (1, 1, 2),
    (1, 2, 3),
    (1, 2, 4),
    (1, 2, 5)
)

select id, s_id, avg(cell_load) over (partition by id, s_id)
from my_table;

 id | s_id |        avg         
----+------+--------------------
  1 |    1 | 1.5000000000000000
  1 |    1 | 1.5000000000000000
  1 |    2 | 4.0000000000000000
  1 |    2 | 4.0000000000000000
  1 |    2 | 4.0000000000000000
(5 rows)

或:

select id, s_id, avg(cell_load)
from my_table
group by 1, 2;

 id | s_id |        avg         
----+------+--------------------
  1 |    1 | 1.5000000000000000
  1 |    2 | 4.0000000000000000
(2 rows)

如果函数是必需的,它应该看起来像这样:

create or replace function cal_average_load(
    _id double precision,
    _s_id double precision)
returns double precision
language sql as $$
    select avg(cell_load)
    from my_table
    where id = _id and s_id = _s_id
$$;

相关问题