Re: week ending

From: "Aaron Bono" <postgresql(at)aranya(dot)com>
To: KeithW(at)narrowpathinc(dot)com
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: week ending
Date: 2006-07-06 15:49:31
Message-ID: bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 7/5/06, Keith Worthington <KeithW(at)narrowpathinc(dot)com> wrote:
>
> Hi All,
>
> I just finished writing a query that groups data based on the week number.
>
> SELECT EXTRACT(week FROM col_a) AS week_number,
> sum(col_b) AS col_b_total
> FROM foo
> WHERE foobar
> GROUP BY EXTRACT(week FROM col_a)
> ORDER BY EXTRACT(week FROM col_a);
>
> I would like to generate the starting date or ending date based on this
> number. IOW instead of telling the user "week number" which they won't
> understand I would like to provide either Friday's date for "week
> ending" or Monday's date for "week beginning".
>
> SELECT <something> AS week_ending,
> sum(col_b) AS col_b_total
> FROM foo
> WHERE foobar
> GROUP BY EXTRACT(week FROM col_a)
> ORDER BY EXTRACT(week FROM col_a);

Try this. It puts Saturday as the Friday before it and Sunday as the Firday
after so if you want Saturday or Sunday to be on different weeks you will
need to do a little tweaking but this should get you going.

SELECT
date_trunc('day', col_a + (interval '1 day' * (5 - extract(dow from
col_a)))) AS week_ending,
sum(col_b) AS col_b_total
FROM foo
GROUP BY
date_trunc('day', col_a + (interval '1 day' * (5 - extract(dow from
col_a))))

In response to

  • week ending at 2006-07-06 04:19:54 from Keith Worthington

Browse pgsql-sql by date

  From Date Subject
Next Message Aaron Bono 2006-07-06 16:02:37 Re: Alternative to serial primary key
Previous Message Scott Marlowe 2006-07-06 14:41:52 Re: Alternative to serial primary key