Re: tricky GROUP BY / JOIN question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: mailreg(at)numerixtechnology(dot)de
Cc: pgsql-sql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: tricky GROUP BY / JOIN question
Date: 2004-11-07 18:31:56
Message-ID: 22995.1099852316@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

T E Schmitz <mailreg(at)numerixtechnology(dot)de> writes:
> This is *almost* what I need:

> SELECT
> BRAND.BRAND_NAME,
> MODEL.MODEL_NAME,
> min (ITEM.PRICE),max (ITEM.PRICE)
> *min (CONDITION.POSITION),max (CONDITION.POSITION)*
> FROM ITEM
> left outer join MODEL on MODEL_PK =ITEM.MODEL_FK
> left outer join BRAND on BRAND.BRAND_PK =MODEL.BRAND_FK
> left outer join CONDITION on CONDITION.CONDITION_PK = ITEM.CONDITION_FK
> group by BRAND.BRAND_NAME,MODEL.MODEL_NAME

> In the result I don't want min/max(POSITION) but CONDITION.NAME of min
> and max(POSITION) for each MODEL.

I think you could do something like

SELECT
BRAND.BRAND_NAME,
MODEL.MODEL_NAME,
min (ITEM.PRICE),max (ITEM.PRICE)
(select name from condition c1 where position = min(condition.position)),
(select name from condition c2 where position = max(condition.position)),
FROM ITEM
left outer join MODEL on MODEL_PK =ITEM.MODEL_FK
left outer join BRAND on BRAND.BRAND_PK =MODEL.BRAND_FK
left outer join CONDITION on CONDITION.CONDITION_PK = ITEM.CONDITION_FK
group by BRAND.BRAND_NAME,MODEL.MODEL_NAME

ie do a sub-select to get the desired name.

You need Postgres 7.4 or later to get this to work --- before that we
would have mis-interpreted the aggregate calls to indicate aggregation
within the sub-selects. The current interpretation is per SQL spec:
since the aggregate argument is a variable of the outer select, the
aggregation occurs with respect to that select, and the aggregate result
is passed down to the sub-select as a scalar.

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message D'Arcy J.M. Cain 2004-11-08 01:56:26 Re: query using a date field that isn't set
Previous Message T E Schmitz 2004-11-07 10:31:08 tricky GROUP BY / JOIN question