2012-12-11 34 views
3

如何在時態數據庫中應用移動平均數。 我的數據包括溫度,我想對每15條記錄應用移動平均值。PostgreSQL中時態數據庫中的移動平均數

+0

您正在使用的Postgre的版本? –

+0

@BhavikAmbani,版本1.16.0。對我的問題重要嗎? –

+2

@ user1885733 1.16.0不是我熟悉的postgresql版本嗎? – hd1

回答

3

您可以觸發查詢如下

marc=# SELECT entity, name, salary, start_date, 
     avg(salary) OVER (ORDER BY entity, start_date 
          ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) 
     FROM salary; 

entity  | name  | salary | start_date |   avg   
-----------+-----------+---------+---------------+---------------------- 
Accounting | millicent | 850.00 | 2006-01-01 | 825.0000000000000000 
Accounting | jack  | 800.00 | 2010-05-01 | 916.6666666666666667 
R&D  | tom  | 1100.00 | 2005-01-01 | 966.6666666666666667 
R&D  | john  | 1000.00 | 2008-07-01 | 933.3333333333333333 
R&D  | maria  | 700.00 | 2009-01-01 | 733.3333333333333333 
R&D  | kevin  | 500.00 | 2009-05-01 | 633.3333333333333333 
R&D  | marc  | 700.00 | 2010-02-15 | 600.0000000000000000 
+0

我遇到了相應的語法錯誤:**錯誤:在「行」處或附近出現語法錯誤** –

+0

我不理解您仍然使用另一個示例更新的表,您可以設計您的來自tbat的查詢。查看我更新的答案。 –

2
WITH moving_avrag AS (
    SELECT 0 AS [lag] UNION ALL 
    SELECT 1 AS [lag] UNION ALL 
    SELECT 2 AS [lag] UNION ALL 
    SELECT 3 AS [lag] --ETC 
) 
SELECT 
    DATEADD(day,[lag],[date]) AS [reference_date], 
    [otherkey1],[otherkey2],[otherkey3], 
    AVG([value1]) AS [avg_value1], 
    AVG([value2]) AS [avg_value2] 
FROM [data_table] 
CROSS JOIN moving_avg 
GROUP BY [otherkey1],[otherkey2],[otherkey3],DATEADD(day,[lag],[date]) 
ORDER BY [otherkey1],[otherkey2],[otherkey3],[reference_date]; 
+0

@ user1885733我不知道如果它甚至不是有效的PostgreSQL語法('#TestDW'不是有效的表名,並且'datead()'不是有效的PostgerSQL函數),它是如何被接受的。 –