Re: Need to show other columns for job table along with summing job cost

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Chuck Roberts <croberts(at)gilsongraphics(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Need to show other columns for job table along with summing job cost
Date: 2015-01-27 21:48:16
Message-ID: 5145.1422395296@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Chuck Roberts <croberts(at)gilsongraphics(dot)com> writes:
> SELECT j.armasterid, j.ccdescription, j.ccpromisedate, j.ccmasterid,
> sum(jc.jcactcost) as sumactcost FROM job j join jobcost jc ON
> (j.ccmasterid = jc.ccmasterid) WHERE (j.ccpromisedate BETWEEN '2014-07-01'
> AND '2014-07-05') AND (jc.jcactcost > 0) group by j.ccmasterid ORDER BY
> j.ccmasterid ;
> Error is: "ERROR: column "j.armasterid" must appear in the GROUP BY clause
> or be used in an aggregate function at character 8"

Is ccmasterid the primary key of "job"? If it's not, this query isn't
well defined: there wouldn't be a unique value of the other "job" columns
for any particular group.

If it is the pkey, more recent versions than PG 8.4 would have accepted
the query as-is, but on 8.4 you'll need a hack. You can either GROUP BY
all the additional columns, eg

group by j.ccmasterid, j.armasterid, j.ccdescription, j.ccpromisedate

or you can use a dummy aggregation for each other column, eg

SELECT max(j.armasterid), max(j.ccdescription), ...

Neither of these hacks will change your results if the query is
well-defined.

If ccmasterid isn't unique, then you need to rethink what you're
grouping by so that the query makes sense.

regards, tom lane

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Chuck Roberts 2015-01-28 13:48:53 Need to show other columns for SUM
Previous Message Gavin Flower 2015-01-27 20:50:57 Re: Need to show other columns for job table along with summing job cost