Search Postgresql Archives

Re: JSONB_AGG: aggregate function calls cannot be nested

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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







[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]

  Powered by Linux