Re: Unexpected results when using GROUP BY GROUPING SETS and bind variables

From: Aner Perez <aner(dot)perez+pgsql-general(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Unexpected results when using GROUP BY GROUPING SETS and bind variables
Date: 2020-09-09 18:58:16
Message-ID: CAP-7WhPMjBUfChLxO8HM5xwE7iL-4HLYV3KxFZ402+1ak3aBiA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Of course, right when I hit send I thought of another option that makes the
SQL a little less readable but perhaps gets rid of the ambiguity. Using
ordinals in the GROUP BY:

SELECT path[1], path[2], path[3], path[4], sum(value)
FROM bind_group_by
GROUP BY GROUPING SETS (
(1, 2, 3, 4),
(1, 2, 3),
(1, 2),
(1),
()
)
ORDER BY 1, 2, 3, 4;

Since I'm generating the SQL I'm not too worried about the readability and
it works with bind variables too. I promise I'll stop thinking after this
one ;-)

Thanks!

- Aner

On Wed, Sep 9, 2020 at 2:45 PM Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:

> Aner Perez <aner(dot)perez+pgsql-general(at)gmail(dot)com> writes:
> > Or if using indexed path elements in the GROUP BY is the issue and I
> should
> > put the array indexing in a subselect and do the aggregation in the outer
> > select. Like this:
>
> > -- Safer Subselect Version --
> > SELECT level1, level2, level3, level4, sum(value)
> > FROM (
> > SELECT path[1] as level1, path[2] as level2, path[3] as level3,
> path[4]
> > as level4, value
> > FROM bind_group_by
> > ) AS expanded
> > GROUP BY GROUPING SETS (
> > (level1, level2, level3, level4),
> > (level1, level2, level3),
> > (level1, level2),
> > (level1),
> > ()
> > )
> > ORDER BY 1, 2, 3, 4;
>
> Yeah, that one looks a lot safer from here. There's no question about
> which expressions are supposed to match what. It should end up with
> the same plan, too.
>
> regards, tom lane
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message JAGMOHAN KAINTURA 2020-09-10 05:09:46 Oracle Associate Array conversion to PostgreSQL
Previous Message Tom Lane 2020-09-09 18:45:53 Re: Unexpected results when using GROUP BY GROUPING SETS and bind variables