pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Aaron Bono <postgresql@aranya.com>
To: KeithW@narrowpathinc.com
Cc: pgsql-sql@postgresql.org
Subject: Re: week ending
Date: Thu, 6 Jul 2006 10:49:31 -0500
Message-ID: <bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com> (raw)
In-Reply-To: <44AC8F6A.4090704@NarrowPathInc.com>
References: <44AC8F6A.4090704@NarrowPathInc.com>

On 7/5/06, Keith Worthington <KeithW@narrowpathinc.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))))

view thread (3+ messages)

Message-ID: <bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com>
Permalink:  ../bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com/
Also on:    postgresql.org/message-id/bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: postgresql@aranya.com, KeithW@narrowpathinc.com
  Subject: Re: week ending
  In-Reply-To: <bf05e51c0607060849r6b76c74eq8a13054da4614c64@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox