我在Postgres数据库中有此表和数据样本
CREATE TABLE testAAA(Id integer PRIMARY KEY, datum date, COLA text, COLB text, COLC text, COLD int);
/* Create few records in this table */
INSERT INTO testAAA VALUES(1,to_date('01/01/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','1');
INSERT INTO testAAA VALUES(2,to_date('01/02/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','1');
INSERT INTO testAAA VALUES(3,to_date('01/03/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','1');
INSERT INTO testAAA VALUES(4,null,'PLANTA','VENDORA','OPA','1');
INSERT INTO testAAA VALUES(5,to_date('01/10/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','5');
INSERT INTO testAAA VALUES(6,to_date('01/10/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','10');
INSERT INTO testAAA VALUES(7,to_date('01/11/2018','dd/mm/yyyy'),'PLANTA','VENDORB','OPA','50');
INSERT INTO testAAA VALUES(8,to_date('01/10/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPA','10');
INSERT INTO testAAA VALUES(9,to_date('01/11/2018','dd/mm/yyyy'),'PLANTA','VENDORA','OPB','5');
COMMIT;
我正在尝试根据条件和组合得出平均值:
SELECT COLA,COLB,COLC,
CASE
WHEN (datum >= now() - interval '6 month') THEN SUM(COLD)/6
ELSE '0'
END AS datum_range
FROM testAAA
group by COLA,COLB,COLC;
我的目标是使用COLA + COLB + COLC组合生成COLD列最近6个月的平均值,如果满足DATE间隔条件,则跳过空值。
现在我遇到此错误:
Error(s), warning(s):
42803: column "testaaa.datum" must appear in the GROUP BY clause or be used in an aggregate function
如何解决以上错误?
答案 0 :(得分:1)
SELECT *,
SUM(COLD) FILTER (WHERE datum >= now() - interval '6 month') OVER (PARTITION BY COLA, COLB, COLC) / 6.0 as avg
FROM testAAA
结果:
| id | datum | cola | colb | colc | cold | avg |
|----|------------|--------|---------|------|------|--------------------|
| 1 | 2018-01-01 | PLANTA | VENDORA | OPA | 1 | 4.166666666666667 |
| 2 | 2018-02-01 | PLANTA | VENDORA | OPA | 1 | 4.166666666666667 |
| 3 | 2018-03-01 | PLANTA | VENDORA | OPA | 1 | 4.166666666666667 |
| 4 | (null) | PLANTA | VENDORA | OPA | 1 | 4.166666666666667 |
| 5 | 2018-10-01 | PLANTA | VENDORA | OPA | 5 | 4.166666666666667 |
| 6 | 2018-10-01 | PLANTA | VENDORA | OPA | 10 | 4.166666666666667 |
| 8 | 2018-10-01 | PLANTA | VENDORA | OPA | 10 | 4.166666666666667 |
| 9 | 2018-11-01 | PLANTA | VENDORA | OPB | 5 | 0.8333333333333334 |
| 7 | 2018-11-01 | PLANTA | VENDORB | OPA | 50 | 8.333333333333334 |
[演示:db <> fiddle] [4]
SUM(...) OVER (PARTITION BY ...)
可以像在GROUP
子句中一样进行SUM聚合,但保留原始行。聚合将添加为单独的列。FILTER
子句允许您过滤聚合函数的输入。因此,您只能汇总datum >= ...
答案 1 :(得分:0)
为什么不只将条件移至where
子句:
SELECT cola, colb, colc, SUM(cold) / 6
FROM testAAA
WHERE datum >= NOW() - INTERVAL '6 MONTH'
GROUP BY cola, colb, colc