Re: aggregate functions are not allowed in UPDATE

From: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
To: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: aggregate functions are not allowed in UPDATE
Date: 2019-01-15 19:17:26
Message-ID: CAADeyWhb9FDLUX=c0quhONxzrkp9j9Gf2yr=Xp0f2Qautiu+oQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Ahh, the subqueries -

On Tue, Jan 15, 2019 at 5:59 PM David G. Johnston <
david(dot)g(dot)johnston(at)gmail(dot)com> wrote:

> On Tue, Jan 15, 2019 at 9:52 AM Alexander Farber
> <alexander(dot)farber(at)gmail(dot)com> wrote:
> >> So calculate the average somewhere else, put the result in a column,
> >> and then reference that column in the SET clause.
> >
> > do you suggest to add a second CTE?
>
> That would qualify as "somewhere else" - as would a simple subquery in
> FROM.
>

they escaped my mind for some reason! :-)

WITH diffs AS (
SELECT
gid,
uid,
played - LAG(played) OVER(PARTITION BY gid ORDER BY played) AS diff
FROM moves
WHERE uid = 1
)
UPDATE users SET avg_time =
(
SELECT
AVG(diff)
FROM diffs
GROUP BY uid
)
WHERE uid = 1;

https://www.db-fiddle.com/f/w1AYGpoZiWW9bLCYjHDk7H/1

seems to work, thank you

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alexander Farber 2019-01-15 19:23:33 Re: aggregate functions are not allowed in UPDATE
Previous Message Rob Sargent 2019-01-15 18:31:40 Re: Refining query statement