Selecting a grouped condition in an Aggregate query
I have a view that averages some statistics by averaging past rows relative to the current outer row. Think of a batting average for each previous at bat for each batter. This works as I would like but, I would like more control over the old_foo.dates
The views idealized query is like this:
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_f开发者_JAVA百科oo.date_ < foo.date_
group by person_id, this_date
;
But what I would really like is to be able set the minimum old_foo.date from the view so I could be able to create arbitrary moving averages on the fly.
Such as:
select * from myview where mindate > now()::date - 10
(mindate is fictitious since I lose it with the group by)
I know I can do this with a function but I would prefer not too. Would CTE's give me more flexibility with what I want?
edit
I can't bring the oldate column to the top level of the view without grouping it (which is not what I want.) I want the view to be general so I could just as easily do a 10 day moving average as a 20 day one, or any date I would like. The olddates in the inner query so I have no access to it once I create a view.
I figured it out :)
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;
Then offset would simulate a function parameter.
Try using the having clause here is some reference
http://www.postgresql.org/docs/8.1/static/tutorial-agg.html
I believe it would look something like this.
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
精彩评论