Re: getting maximum entry from a sum()

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jan Danielsson <jan(dot)danielsson(at)gmail(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: getting maximum entry from a sum()
Date: 2006-10-06 14:49:42
Message-ID: 20747.1160146182@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Jan Danielsson <jan(dot)danielsson(at)gmail(dot)com> writes:
> Essentially, I want:

> select dt,sum(amount) as asum where asum=(select max(asum) ...) group by dt

There are a couple ways you could do it:

* HAVING clause:

select dt,sum(amount) as asum
group by dt
having sum(amount) = (select max(asum) ...)

* ORDER BY/LIMIT:

select dt,sum(amount) as asum
group by dt
order by asum desc
limit 1

The first is standard SQL, the second isn't (no LIMIT in the spec)
but the second is probably more efficient.

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Darren R 2006-10-06 15:51:16 Re: postgresql db account
Previous Message A. Kretschmer 2006-10-06 14:21:24 Re: getting maximum entry from a sum()