pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: David Johnston <polobo@yahoo.com>
To: John Fabiani <johnf@jfcomputer.com>
Cc: pgsql-sql@postgresql.org <pgsql-sql@postgresql.org>
Subject: Re: using the aggregate function max()
Date: Thu, 22 Sep 2011 23:14:58 -0400
Message-ID: <5EABD4DE-5CB8-4C65-A1FF-3166A683EE3F@yahoo.com> (raw)
In-Reply-To: <201109221949.20671.johnf@jfcomputer.com>
References: <201109221949.20671.johnf@jfcomputer.com>



On Sep 22, 2011, at 22:49, John Fabiani <johnf@jfcomputer.com> wrote:

> Hi,
> I need a little help understanding how to attack this problem.  
> 
> I need to find the max(date) of a field but I need that value later in my 
> query.
> 
> If I
> select max(x.date_field) as special_date from (select date_field) from table 
> where ...)x 
> 
> I get one row and column.
> 
> But now I want to use that field in the rest of the query
> 
> select y.*,  max(x.date_field) as special_date from (select date_field) from 
> table where ...)x  
> from aTable y where y.somefield = special_date.
> 
> The above only returns one row and one column the "special_date."
> 
> How can I use the aggregate field "special_date" in the rest of the query?  Or 
> is there some other way?
> 
> Johnf
> 
> -- 
> Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-sql

Your query above is syntactically invalid.  Try this.

WITH max_date AS ( select max(datefield) AS specialdate from ...)
SELECT *
FROM table
JOIN max_date ON table.somefield = max_date.specialdate;

You can use a online query instead of the WITH if desired, same effect.

You could also drop the join and use the max_date CTE in a WHERE clause:

... FROM table WHERE table.somefield = (SELECT specialdate FROM max_date)

David J





view thread (4+ messages)  latest in thread

Message-ID: <5EABD4DE-5CB8-4C65-A1FF-3166A683EE3F@yahoo.com>
Permalink:  ../5EABD4DE-5CB8-4C65-A1FF-3166A683EE3F@yahoo.com/
Also on:    postgresql.org/message-id/5EABD4DE-5CB8-4C65-A1FF-3166A683EE3F@yahoo.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: polobo@yahoo.com, johnf@jfcomputer.com
  Subject: Re: using the aggregate function max()
  In-Reply-To: <5EABD4DE-5CB8-4C65-A1FF-3166A683EE3F@yahoo.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox