Re: JSONB_AGG: aggregate function calls cannot be nested

From: Thomas Kellerer <shammat(at)gmx(dot)net>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: JSONB_AGG: aggregate function calls cannot be nested
Date: 2021-02-20 20:01:23
Message-ID: 1a210dd1-74b3-d162-3579-ba6e79a72be3@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alexander Farber schrieb am 20.02.2021 um 19:39:
> So I am trying:
>
> # SELECT
>                 JSONB_AGG(TO_CHAR(finished, 'YYYY-MM-DD')) AS day,
>                 JSONB_AGG(SUM(CASE WHEN reason='regular' or reason='resigned' THEN 1 ELSE 0 END)::int) AS completed,
>                 JSONB_AGG(SUM(CASE WHEN reason='expired' THEN 1 ELSE 0 END)::int) AS expired
>         FROM words_games
>         WHERE finished > CURRENT_TIMESTAMP - INTERVAL '2 week'
>         GROUP BY day
>         ORDER BY day;
> ERROR:  aggregate function calls cannot be nested
> LINE 3:                 JSONB_AGG(SUM(CASE WHEN reason='regular' or ...

You need a second level of grouping:

select day as day,
jsonb_agg(completed) as completed,
jsonb_agg(expired) as expired)
from (
SELECT TO_CHAR(finished, 'YYYY-MM-DD') AS day,
SUM(CASE WHEN reason='regular' or reason='resigned' THEN 1 ELSE 0 END)::int AS completed,
SUM(CASE WHEN reason='expired' THEN 1 ELSE 0 END)::int) AS expired
FROM words_games
WHERE finished > CURRENT_TIMESTAMP - INTERVAL '2 week'
GROUP BY day
) t
GROUP BY day
ORDER BY day;

Btw:

SUM(CASE WHEN reason='regular' or reason='resigned' THEN 1 ELSE 0 END)::int AS completed,

can also be written as

count(*) filter (where reason in ('regular', 'resigned') as completed

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Dan Nessett 2021-02-21 15:37:45 Getting unexpected results from regexp_replace
Previous Message David G. Johnston 2021-02-20 19:49:35 Re: JSONB_AGG: aggregate function calls cannot be nested