2010-11-23 62 views
0

我有一個視圖,通過將相對於 的過去行平均到某個統計數據的當前外行。考慮每個擊球手每次擊球的平均擊球次數。這個工程,我想,但我想更多的控制權old_foo.dates選擇聚合查詢中的分組條件

理想化查詢的觀點是這樣的:

create view myview as 
select 
    avg(old_foo.stuff), 
    foo.person_id, 
    foo.date_ as this_date 

from 
    foo, 
    join (select stuff, person_id, date_ from foo) as old_foo 
     on old_foo.date_ < foo.date_ 

group by person_id, this_date 
; 

但我真的想的是能夠設定的最低從 視圖old_foo.date,所以我可以創建任意移動平均線動態

如:

select * from myview where mindate > now()::date - 10 

(MINDATE是虛構的,因爲我通過跟團失去它)

我知道我可以用一個功能做到這一點,但我不喜歡太。 CTE會給我更多的靈活性嗎?

編輯

我不能把oldate列視圖的頂層不進行分組它(這不是我想要的。)我想的觀點是一般,所以我可以只是輕鬆地做一個20天的一天或我想要的任何日期的10日均線。在內部查詢中的舊版本,所以我創建視圖後無法訪問它。

回答

1

我想通了:)

create view myview as 
select 
    avg(old_foo.stuff), 
    foo.person_id, 
    foo.date_ as this_date, 
    offset 
from 
    generate_series(1, 100) as offset, 
    foo, 
    join (select stuff, person_id, date_ from foo) as old_foo 
     on old_foo.date_ < foo.date_ 
     and old_foo.date_ > foo.date_ - offset 

group by person_id, this_date, offset 
; 


select * from myview where offset = 10; 

那麼offset模擬功能參數。

0

嘗試此處使用having子句一定的參考

http://www.postgresql.org/docs/8.1/static/tutorial-agg.html

我相信它會是這個樣子。

create view myview as 
select 
    avg(old_foo.stuff), 
    foo.person_id, 
    foo.date_ as this_date 

from 
    foo, 
    join (select stuff, person_id, date_ from foo) as old_foo 
     on old_foo.date_ < foo.date_ 

group by person_id 
having min(foo.date_) <= now() - 10 
+0

我不想在視圖中對條件進行硬編碼。 – 2010-11-23 01:35:16