postgresql numrange的平均值

时间:2017-12-05 12:29:04

标签: postgresql range average

我有一个包含以下数据的Postgresql表

Power_range;unit; Date
[0.055,0.065];un_MW_el;14.01.1985
[0.02,0.02];un_MW_el;22.08.1985
[0.075,0.085];un_MW_el;09.04.1986
[0.055,0.055];un_MW_el;01.08.1986
[0.065,0.065];un_MW_el;19.01.1987
[0.075,0.075];un_MW_el;16.04.1987
[0.055,0.055];un_MW_el;15.05.1987

我们如何查询列出每年/每行的平均值?

最终结果应该是

0.060;1985
0.2;1985
0.80;1986 
0.055;1986
0.065;1987
0.075;1987
0.055;1987

1 个答案:

答案 0 :(得分:0)

我不确定是否有内联avg数学函数,但您可以使用arythmetics轻松模拟它:

t=# select ((lower(power_range) + upper(power_range))/2)::float(2),extract(year from d) avg From rt;
 float4 | avg
--------+------
   0.06 | 1985
   0.02 | 1985
   0.08 | 1986
  0.055 | 1986
  0.065 | 1987
  0.075 | 1987
  0.055 | 1987
(7 rows)

从样本中创建rt:

t=# create table rt(Power_range numrange, unit text, d date);
CREATE TABLE
t=# copy rt from stdin delimiter ';';

https://www.postgresql.org/docs/current/static/functions-range.html