Re: Creative use of CASE in a GROUP BY clause

From: Masaru Sugawara <rk73(at)sea(dot)plala(dot)or(dot)jp>
To: "Dorian Taylor" <leg0(at)hotmail(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Creative use of CASE in a GROUP BY clause
Date: 2002-03-18 15:58:25
Message-ID: 20020319004233.2FBF.RK73@sea.plala.or.jp
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Mon, 18 Mar 2002 13:14:46
"Dorian Taylor" <leg0(at)hotmail(dot)com> wrote:

> I'm trying to figure out how to craft a query that I can embed into a piece
> of code that can be passed a bind value in order to dictate how it should
> behave on GROUP BY, sparing me from having to write separate queries for N
> functions and/or columns I may want to group my query by.
>
> e.g. SELECT COUNT(foo) FROM bar GROUP BY CASE (? IS NOT NULL) THEN thiscol
> ELSE thatcol END
>
> If thiscol and thatcol aren't the same type, the CASE bombs out. I suppose

If so, you may need to cast one of them.

e.g.
SELECT COUNT(foo) FROM bar
GROUP BY CASE WHEN (? IS NOT NULL)
THEN thiscol::TEXT
ELSE thatcol -- if the type of thatcol is TEXT
END;

> ultimately it would be a matter of reducing each column definition in the
> CASE to a boolean expression, but I'm not sure what that would syntactically
> look like, as simply declaring a column in GROUP BY is obviously shorthand
> for something.
>

Regards,
Masaru Sugawara

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Stephan Szabo 2002-03-18 22:51:24 Re: Line Numbering in SELRCT Output
Previous Message Dorian Taylor 2002-03-18 13:14:46 Creative use of CASE in a GROUP BY clause