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

时间:2017-08-10 08:54:10

标签: sql postgresql dataset

我的功能有问题,我需要按两列分组并取另一列的平均值。

为什么以下不起作用?

const data = { a: '213', b: 'asv', c: 'sdfs' };
let printData = Object.entries(data).map(entry => entry.join(': ')).join('<br/>');
console.log(printData); // "a: 213<br/>b: asv<br/>c: sdfs"

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

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;
$$;

1 个答案:

答案 0 :(得分:3)

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

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
$$;