Re: interval questions

From: Michael Blakeley <mike(at)blakeley(dot)com>
To: Ed Loehr <eloehr(at)austin(dot)rr(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: interval questions
Date: 2000-06-02 02:29:54
Message-ID: p04320425b55ccad6162b@blakeley.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

At 10:21 PM -0500 6/1/2000, Ed Loehr wrote:
>Michael Blakeley wrote:
>>
>> CREATE TABLE EVENTS( stamp date, id varchar(16), event varchar(128) );
>>
>> I'm trying to find the average age of the records. I've gotten as far as:
>> SELECT DISTINCT ON(id) age(stamp) FROM EVENTS;
>>
>> Now, I need the DISTINCT ON(id), but that means I can't simply
>>avg() the age:
>> ERROR: Attribute events.id must be GROUPed or used in an
>> aggregate function
>>
>
>Interesting problem. Would this do it?
>
> select into temp_age id, sum(age(stamp)) as age_sum, count(id)
> from EVENTS group by id;
>
>followed by
>
> select avg(age_sum/count) from temp_age;

I oversimplified - I left out the outer join, which I was performing
in the wrong (non-unique id) direction. I wanted to query for the age
of ids that have had events (recently, but I'll omit that part). The
following is a little closer to what I was trying to do:
CREATE TABLE IDS (id varchar(16) primary key, created date);
SELECT DISTINCT ON(id) avg(age(IDS.created))) FROM EVENTS WHERE id=IDS.id;

Reversing the join gives me unique ids, and allowed me to leave out
the DISTINCT ON clause. So avg() now works, and gives me the single
number I was after. Like:
SELECT AVG(AGE(created))) FROM IDS WHERE id=EVENTS.id;

Thanks for the help - it wasn't until I explained the problem
properly that I figured it out :-).

-- Mike

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2000-06-02 02:39:47 Re: query optimiser changes 6.5->7.0
Previous Message Ron Chmara 2000-06-02 01:21:51 Re: PostgreSQL article in LinuxWorld