Re: STRING_AGG and GROUP BY

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Alexander Farber <alexander(dot)farber(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: STRING_AGG and GROUP BY
Date: 2018-03-19 21:02:09
Message-ID: CAKFQuwb0W1r-=6vy=SOWLWtjSc=KP+D8gEeTo3uYSq4k5GDPTg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Mar 19, 2018 at 1:54 PM, Alexander Farber <
alexander(dot)farber(at)gmail(dot)com> wrote:

>
> I've come up with the following query, wonder if you meant something
> similar -
>
> http://sqlfiddle.com/#!17/4ef8b/48
>
> WITH cte1 AS (
> SELECT
> mid,
> STRING_AGG(x->>'letter', '') AS tiles
> FROM (
> SELECT
> mid,
> JSONB_ARRAY_ELEMENTS(m.tiles) AS x
> FROM moves m
> WHERE m.gid = 1
> ) AS z
> GROUP BY mid),
> cte2 AS (
> SELECT
> mid,
> STRING_AGG(y, ', ') AS words
> FROM (
> SELECT
> mid,
> FORMAT('%s (%s)', s.word, s.score) AS y
> FROM scores s
> WHERE s.gid = 1
> ) AS z
> GROUP BY mid)
> SELECT mid, tiles, words
> FROM cte1 JOIN cte2 using (mid) ORDER BY mid ASC;
>
>
​​Yes. It does end up presuming that the sets moves.mid and scores.mid
​are identical but that is probably a safe assumption. Repetition of m.gid
= 1 is worth avoiding in theory though depending on how its done the
solution can be worse than the problem (if the planner ends up unable to
push the predicate down).

​David J.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Geoghegan 2018-03-19 21:12:29 Re: found xmin from before relfrozenxid on pg_catalog.pg_authid
Previous Message Jeremy Finzel 2018-03-19 20:55:44 Re: found xmin from before relfrozenxid on pg_catalog.pg_authid