Re: Formatting Functions and Group By

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Terry Brick <terry_brick2000(at)yahoo(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Formatting Functions and Group By
Date: 2004-04-13 17:33:18
Message-ID: 24390.1081877598@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Terry Brick <terry_brick2000(at)yahoo(dot)com> writes:
> I'm porting a bunch of queries from MySQL to Postgres 7.4 and am having a problem with one
> particular area. For example, a query like this works in MySQL:

> select
> to_char(myCol,'Mon YY')
> from
> myTable
> group by
> to_char(myCol,'MM YYYY')
> order by
> to_char(myCol,'MM YYYY')

Ah, good ol' MySQL :-( ... let the user do what he wants whether the
result is well defined or not ...

I'd suggest doing the grouping/ordering numerically rather than
textually. For instance,

select
to_char(date_trunc('month', myCol), 'Mon YY')
from
myTable
group by
date_trunc('month', myCol)
order by
date_trunc('month', myCol);

Now this assumes you really want a time-based ordering, which the quoted
example doesn't give --- you've got month sorting to the left of year,
is that really what you want? If it is then you'd need to go

group by
date_trunc('month', myCol)
order by
to_char(date_trunc('month', myCol), 'MM YYYY')

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Greg Stark 2004-04-13 17:36:01 Re: trigger/for key help
Previous Message Bruno Wolff III 2004-04-13 16:45:18 Re: Formatting Functions and Group By