Multiple columns w/single aggregate

Started by Robert M. Craver IIabout 25 years ago3 messagesgeneral
Jump to latest
#1Robert M. Craver II
rob.craver@home.com

I cannot successfully execute the sql statement:

SELECT percentage, MAX(start_date) FROM sometable
WHERE id = 1

I get the error message:

ERROR: Attribute sometable.percentage must be GROUPed
or used in an aggregate function

I know that I have seen examples of selecting multiple columns with a
single colunn aggregate function. In fact, the new 'PostgreSQL:
Introductions and Concepts' book by Bruce Momjian has two on page 53.
Does anyone know why this doesn't work?

Thanks in advance.

#2Ian Harding
iharding@pakrat.com
In reply to: Robert M. Craver II (#1)
Re: Multiple columns w/single aggregate

"Robert M. Craver II" wrote:

I cannot successfully execute the sql statement:

SELECT percentage, MAX(start_date) FROM sometable
WHERE id = 1

I get the error message:

ERROR: Attribute sometable.percentage must be GROUPed
or used in an aggregate function

I know that I have seen examples of selecting multiple columns with a
single colunn aggregate function. In fact, the new 'PostgreSQL:
Introductions and Concepts' book by Bruce Momjian has two on page 53.
Does anyone know why this doesn't work?

Thanks in advance.

True, but you need to group by the non-aggregate columns. In your case,
just add

GROUP BY percentage

This will give you a listing of all distinct 'percentage' values, and
the maximum of their 'start_date' values, that have id=1. It will blow
up if there are any NULL in 'percentage' unlike some inferior products
that simply silently eliminate them for you.

Ian

#3Bruce Momjian
bruce@momjian.us
In reply to: Robert M. Craver II (#1)
Re: Multiple columns w/single aggregate

I cannot successfully execute the sql statement:

SELECT percentage, MAX(start_date) FROM sometable
WHERE id = 1

Sure, you need GROUP BY. How does it know which columns to use for the
MAX.

I get the error message:

ERROR: Attribute sometable.percentage must be GROUPed
or used in an aggregate function

I know that I have seen examples of selecting multiple columns with a
single colunn aggregate function. In fact, the new 'PostgreSQL:
Introductions and Concepts' book by Bruce Momjian has two on page 53.
Does anyone know why this doesn't work?

Thanks in advance.

-- 
  Bruce Momjian                        |  http://candle.pha.pa.us
  pgman@candle.pha.pa.us               |  (610) 853-3000
  +  If your life is a hard drive,     |  830 Blythe Avenue
  +  Christ can be your backup.        |  Drexel Hill, Pennsylvania 19026