Re: Converting row elements into a arrays?

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: Ron <ronljohnsonjr(at)gmail(dot)com>
Cc: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Converting row elements into a arrays?
Date: 2023-03-03 20:51:03
Message-ID: CAHyXU0xeS=vu-M3z=8EXi6N7ZqhAV+a-fy2ZMQxGgsMgPiw2LA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Mar 2, 2023 at 3:47 PM Ron <ronljohnsonjr(at)gmail(dot)com> wrote

> I'm used to the bog standard COUNT, AVG, MIN, MAX, SUM. It didn't occur to
> me that there would be others...
>

wait until you find out you can write your own:

CREATE OR REPLACE FUNCTION agg_leftagg(l TEXT, r anyelement) returns text as
$$
BEGIN
RETURN CASE
WHEN l IS NOT NULL THEN format('%s-%s', l, r)
ELSE r::TEXT
END;
END;
$$ LANGUAGE PLPGSQL;

CREATE AGGREGATE leftagg(anyelement) (SFUNC=agg_leftagg, STYPE=TEXT);

CREATE TEMP TABLE s AS SELECT generate_series(1,10) s;

SELECT leftagg(s) FROM s GROUP BY random() > .5;

postgres=# SELECT leftagg(s) FROM s GROUP BY random() > .5;
leftagg
────────────
2-3-5-6-10
1-4-7-8-9
(2 rows)

this is why I fell in love with postgres 20 years ago, and never looked back

merlion

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ron 2023-03-03 21:55:24 Re: Dropping behavior for unique CONSTRAINTs
Previous Message Thorsten Glaser 2023-03-03 19:32:14 Re: DISTINCT *and* ORDER BY in aggregate functions on expressions(!)y