这样的表:
DATE ACTYPE DICT
2017-01-01 A319 2
2017-01-01 A320 2
2017-01-02 A319 5
2017-01-02 A320 3
2017-01-03 A319 1
2017-01-03 A320 6
2017-01-04 A319 3
2017-01-04 A320 9
我想得到这样的结果:
DATE ACTYPE DICT DICT_MOV
2017-01-03 A319 1 2.666666
2017-01-03 A320 6 3.666666
2017-01-04 A319 3 3
2017-01-04 A320 9 6
根据ACTYPE分组的平均值,DICT_MOV将近三天。 例如:DICT_MOV 3 = 5,1,3平均值; DICT_MOV 6 = 3,6,9平均值
答案 0 :(得分:3)
您可以将AVG
用作范围窗口的分析函数:
SELECT t.*,
AVG( dict ) OVER (
PARTITION BY actype
ORDER BY "DATE"
RANGE BETWEEN INTERVAL '2' DAY PRECEDING
AND INTERVAL '0' DAY FOLLOWING
) AS dict_mov
FROM your_table t
ORDER BY "DATE", actype
答案 1 :(得分:0)
此查询假设(date,actype)是您的表的PRIMARY KEY,并且您希望获得最近3天的结果 - 而不是连续的。对于连续日期,您可以使用MTO的答案:
SELECT "date", actype, dict,
AVG(dict) OVER (
PARTITION BY actype
ORDER BY "date"
rows BETWEEN 2 PRECEDING AND CURRENT ROW
) AS dict_mov
FROM table_name
ORDER BY "date", actype;
如果(date,actype)不是你的表的PRIMARY KEY,然后是table_name,你必须使用子查询来计算SUM(dict)GROUP BY“date”,actype。